ds18b20温度传感器代码
时间: 2023-11-09 20:09:18 浏览: 44
以下是ds18b20温度传感器的Arduino代码:
```
#include <OneWire.h>
// DS18B20 data pin
#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
void setup() {
Serial.begin(9600);
}
void loop() {
byte data[12];
byte addr[8];
// Search for a device on the bus
if (!oneWire.search(addr)) {
// Resets the search and waits for a new device
oneWire.reset_search();
delay(250);
return;
}
// Verify if the device is a DS18B20
if (addr[0] != 0x28) {
return;
}
// Issue a temperature conversion command
oneWire.reset();
oneWire.select(addr);
oneWire.write(0x44);
// Wait for conversion to complete (750ms for 12-bit resolution)
delay(750);
// Read the scratchpad data
oneWire.reset();
oneWire.select(addr);
oneWire.write(0xBE);
// Read 9 bytes (scratchpad is 8 bytes + 1 byte for CRC)
for (int i = 0; i < 9; i++) {
data[i] = oneWire.read();
}
// Verify the CRC
if (OneWire::crc8(data, 8) != data[8]) {
Serial.println("CRC Error");
return;
}
// Convert the raw temperature data to Celsius
int16_t rawTemp = (data[1] << 8) | data[0];
float celsius = (float)rawTemp / 16.0;
// Print the temperature in Celsius and Fahrenheit
Serial.print("Temperature: ");
Serial.print(celsius);
Serial.print(" °C, ");
Serial.print(celsius * 1.8 + 32.0);
Serial.println(" °F");
}
```
这个代码使用了OneWire库来与DS18B20温度传感器进行通信。它通过搜索总线上的所有设备来查找DS18B20,然后发送温度转换命令并等待转换完成。接下来,它读取DS18B20的scratchpad数据并验证CRC,然后将原始温度数据转换为摄氏温度并打印输出。
阅读全文