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

两个传感器连接在同一引脚上,如Arduino的数字引脚2.这种直插的DS18B20需要接上拉电阻,在DQ和VCC之间接4.7K-10K电阻。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | / / 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口,以此实现多点组网.
参考
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!