DS18B20一直输出-127 ??
一、硬件连线

将相应的线接到ESP wroom 32

二、代码
- 先在PlatformIO的library添加onWire库和DallasTemperature
库
#include <Arduino.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#define DS18B20PIN 4
OneWire onWire(DS18B20PIN);
DallasTemperature sensors(&onWire);
void setup()
{
Serial.begin(115200);
sensors.begin();
}
void loop()
{
sensors.requestTemperatures(); // Send the command to get temperatures
float ds_num = sensors.getTempCByIndex(0);
Serial.println(ds_num);
}
三、遇到的问题
代码编译运行没有问题,但是在串口看到都是输出-127。

网上看了解决方案是这样说的:
- ESP32 的GPIOx与Dx可能不是一个口,所以定义的时候得注意下那个IO口是不是对的。
- 电源没有正确接入
- 需要外加一个上拉电阻
我遇到的是第3个。后来查看ESP32 的数据手册知道,有点GPIO是不提供上拉的。而且DS18B20的手册也有说,需要加上拉电阻。原因是这样的,IO作为输出时,自带锁存功能,也就是写1后,输出一直是1(锁存器上的值),引脚上可能被外部电路影响而不是1了。所以需要上拉。

加了上拉电阻之后,就能够输出正常的温度值了。


如有见解,欢迎留言指教。