基于Arduino UNO的DS18B20多点组网测温

文章介绍了如何使用ArduinoUNO和DallasTemperature库与OneWire库,通过单总线协议连接和通信多个DS18B20温度传感器。每个DS18B20具有唯一的64位地址,通过库函数可扫描并读取所有传感器的温度。在Arduino的数字引脚上连接传感器并添加上拉电阻,程序会自动检测并显示设备数量及温度读数,实现精准且节省IO口的多传感器测量。
摘要由CSDN通过智能技术生成

写在前面

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)

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值