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

写在前面

DS18B20基于单总线协议,多个DS18B20可以连接在同一个引脚上,通过单总线扫描可以得到地址,并分别对某个地址上的DS18B20进行通信(发命令开启温度转换)完成测温。

设备地址(64位)

每个传感器都有一个唯一的64位序列号,其中包含一个8位的家族代码,一个48位的序列号和一个8位的CRC校验码2。您可以使用相应的函数来扫描总线上所有连接的传感器,并打印出它们的地址.

引入

以Arduino UNO 为例 ,先在库中添加 Ooe Wire 和DallasTemperature的库。

基于Arduino UNO的DS18B20多点组网测温_第1张图片

两个传感器连接在同一引脚上,如Arduino的数字引脚2.这种直插的DS18B20需要接上拉电阻,在DQ和VCC之间接4.7K-10K电阻。

// Include the required Arduino libraries:
#include 
#include 

// 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口,以此实现多点组网.

基于Arduino UNO的DS18B20多点组网测温_第2张图片

参考

DS18B20 Temperature Sensor Arduino Tutorial (4 Examples) (makerguides.com)

你可能感兴趣的:(单片机,嵌入式硬件)