You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MacOS Monterey下VSCode+ESP32模拟温度读取异常求助

ESP32模拟温度计在MacOS PlatformIO中输出异常的排查与解决

核心问题与修复步骤

1. ADC分辨率不匹配(最可能的根因)

ESP32采用12位ADC,原始读数范围是0-4095,但你的代码沿用了Arduino Uno等10位ADC板子的1023作为最大值,导致电压计算严重偏差,最终温度输出异常。

修复代码:

// 替换原有的电压计算行
volts = tempVal / 4095.0; // ESP32是12位ADC,最大值为4095

2. 串口波特率兼容性问题

MacOS对超高波特率(如921600)的串口支持不稳定,建议降低到通用波特率:

  • 修改代码中的Serial.begin(921600);为Serial.begin(115200);
  • 同时在PlatformIO串口监视器中选择相同的波特率(点击监视器窗口右下角波特率选项切换)

3. 字符串换行符冗余问题

Serial.println本身会自动添加换行符,你代码中额外写入的换行符会导致输出格式混乱,修正如下:

// 原冗余换行代码
Serial.println(" degrees C\n");
// 改为
Serial.println(" degrees C");

// 同理修改华氏度输出行
Serial.println(" degrees F");

4. 引脚ADC可用性确认

ESP32的GPIO2属于ADC2通道,若后续启用WiFi会被占用,当前仅读取温度可正常使用。若问题仍存在,可切换到ADC1无复用冲突的引脚(如GPIO34、GPIO35)。

完整修复后的代码

#include <Arduino.h>

const int tempPin = 2;

int tempVal;
float volts;
float tempC;
float tempF;

void setup()
{
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.begin(115200);
  Serial.println("Hello from the setup");
}

void loop()
{
  tempVal = analogRead(tempPin);
  volts = tempVal / 4095.0; // 适配ESP32的12位ADC
  tempC = (volts - 0.5) * 100;
  tempF = tempC * 1.8 + 32; // 直接用摄氏度转换,代码更简洁

  Serial.print(" Temperature is:   ");
  Serial.print(tempC);
  Serial.println(" degrees C");

  Serial.print(" Temperature is:   ");
  Serial.print(tempF);
  Serial.println(" degrees F");

  delay(1000);
}

内容的提问来源于stack exchange,提问作者Alan Gabriel Reyes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 23:25:19