基于Arduino UNO的DS18B20多点组网测温
写在前面
DS18B20基于单总线协议,多个DS18B20可以连接在同一个引脚上,通过单总线扫描可以得到地址,并分别对某个地址上的DS18B20进行通信(发命令开启温度转换)完成测温。
设备地址(64位)
每个传感器都有一个唯一的64位序列号,其中包含一个8位的家族代码,一个48位的序列号和一个8位的CRC校验码2。您可以使用相应的函数来扫描总线上所有连接的传感器,并打印出它们的地址.
引入
以Arduino UNO 为例 ,先在库中添加 Ooe Wire 和DallasTemperature的库。

两个传感器连接在同一引脚上,如Arduino的数字引脚2.这种直插的DS18B20需要接上拉电阻,在DQ和VCC之间接4.7K-10K电阻。
// Include the required Arduino libraries:
#include <OneWire.h>
#include <DallasTemperature.h>
// Define to which pin of the Arduino the 1-Wire bus is connected:
#define ONE_WIRE_BUS 2
// Create a new instance of the oneWire class to communicate with any OneWire device:
OneWire oneWire(ONE_WIRE_BUS);
// Pass oneWire reference to Dallas Temperature library:
DallasTemperature sensors(&oneWire);
void setup() {
// Start serial communication for debugging purposes:
Serial.begin(9600);
// Start up the library:
sensors.begin();
}
void loop() {
// Send command to get temperatures from all devices on bus:
sensors.requestTemperatures();
// Get number of devices on bus:
int numberOfDevices = sensors.getDeviceCount();
// Print number of devices on bus:
Serial.print("Number of devices: ");
Serial.println(numberOfDevices);
// Loop through each device and print out address and temperature:
for (int i = 0; i < numberOfDevices; i++) {
// Use a variable to store a found device address
DeviceAddress tempDeviceAddress;
// Search for devices on bus and assign based on an index.
if (sensors.getAddress(tempDeviceAddress, i)) {
Serial.print("Found '1-Wire' device with address:\n\r");
printAddress(tempDeviceAddress);
Serial.print("\n\r");
// Print temperature for found device
float tempC = sensors.getTempC(tempDeviceAddress);
Serial.print("Temperature: ");
Serial.print(tempC);
Serial.println(" °C");
}
else {
Serial.print("Found ghost device at ");
Serial.print(i);
Serial.println(" but could not detect address. Check power and cabling");
}
delay(1000);
}
}
// Function that prints a device address
void printAddress(DeviceAddress deviceAddress) {
for (uint8_t i = 0; i < 8; i++) {
if (deviceAddress[i] < 16)
Serial.print("0");
Serial.print(deviceAddress[i], HEX);
}
}
效果
立杆见影。DS18B20比DHT11更精准。又因为是单总线的通信协议,省IO口,以此实现多点组网.

参考
DS18B20 Temperature Sensor Arduino Tutorial (4 Examples) (makerguides.com)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?