DS18B20进行温度测量的代码
时间: 2023-09-20 07:03:29 浏览: 32
以下是使用DS18B20进行温度测量的基本代码:
```
#include <OneWire.h>
// Data wire is connected to digital pin 2
#define ONE_WIRE_BUS 2
// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(ONE_WIRE_BUS);
void setup() {
Serial.begin(9600);
}
void loop() {
// Reset the OneWire bus
oneWire.reset();
// Send command to start temperature conversion
oneWire.write(0x44, 1);
// Wait for conversion to complete
delay(1000);
// Reset the OneWire bus again
oneWire.reset();
// Send command to read temperature
oneWire.write(0xBE);
// Read temperature data
byte data[9];
for (int i = 0; i < 9; i++) {
data[i] = oneWire.read();
}
// Calculate temperature value
int16_t rawTemp = (data[1] << 8) | data[0];
float tempC = (float)rawTemp / 16.0;
// Print temperature value
Serial.print("Temperature: ");
Serial.print(tempC);
Serial.println(" °C");
delay(1000);
}
```
该代码使用OneWire库与DS18B20通信。它发送命令来启动温度转换,等待转换完成,然后读取温度数据并计算温度值。最后,它打印温度值到串口监视器。请注意,代码中的数据线连接到数字引脚2。如果您将DS18B20连接到不同的引脚,请相应地更改ONE_WIRE_BUS定义。