ds18b20 代码
时间: 2023-11-09 16:09:26 浏览: 175
以下是 DS18B20 温度传感器的 Arduino 代码示例:
```
#include <OneWire.h>
// DS18B20 数据线连接到 Arduino 引脚 2
#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
void setup() {
Serial.begin(9600);
}
void loop() {
byte i;
byte present = 0;
byte type_s;
byte data[12];
byte addr[8];
if ( !oneWire.search(addr)) {
Serial.println("No more addresses.");
oneWire.reset_search();
delay(250);
return;
}
Serial.print("ROM =");
for( i = 0; i < 8; i++) {
Serial.write(' ');
Serial.print(addr[i], HEX);
}
if (OneWire::crc8(addr, 7) != addr[7]) {
Serial.println("CRC is not valid!");
return;
}
Serial.println();
// 温度传感器类型判断
switch (addr[0]) {
case 0x10:
Serial.println(" Chip = DS18S20"); // or old DS1820
type_s = 1;
break;
case 0x28:
Serial.println(" Chip = DS18B20");
type_s = 0;
break;
case 0x22:
Serial.println(" Chip = DS1822");
type_s = 0;
break;
default:
Serial.println("Device is not a DS18x20 family device.");
return;
}
// 温度读取
oneWire.reset();
oneWire.select(addr);
oneWire.write(0x44,1); // 开始温度转换,参数为 1 表示使用最高分辨率
delay(1000); // 等待转换完成
present = oneWire.reset();
oneWire.select(addr);
oneWire.write(0xBE); // 发送读取命令
for ( i = 0; i < 9; i++) { // 读取 9 字节数据
data[i] = oneWire.read();
}
int16_t raw = (data[1] << 8) | data[0];
if (type_s) {
raw = raw << 3; // 9 bit resolution default
if (data[7] == 0x10) {
// "count remain" gives full 12 bit resolution
raw = (raw & 0xFFF0) + 12 - data[6];
}
} else {
byte cfg = (data[4] & 0x60);
if (cfg == 0x00) raw = raw & ~7; // 9 bit resolution, 93.75 ms
else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
//// default is 12 bit resolution, 750 ms conversion time
}
float celsius = (float)raw / 16.0;
Serial.print(" Temperature = ");
Serial.print(celsius);
Serial.println(" Celsius, ");
}
```
阅读全文