写一段ds18b20温度传感器的代码
时间: 2023-12-01 08:28:22 浏览: 105
#include <OneWire.h>
// Pin used for the OneWire communication
#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() {
byte i;
byte present = 0;
byte type_s;
byte data[12];
byte addr[8];
// Reset the OneWire bus
oneWire.reset_search();
// Search for OneWire devices on the bus
while (oneWire.search(addr)) {
// Check if the device found is a DS18B20
if (addr[0] == 0x28) {
// Send the device a command to start temperature conversion
oneWire.reset();
oneWire.select(addr);
oneWire.write(0x44, 1);
// Wait for the temperature conversion to complete
delay(1000);
// Reset the OneWire bus and select the device
oneWire.reset();
oneWire.select(addr);
// Send the device a command to read the scratchpad memory
oneWire.write(0xBE);
// Read the scratchpad memory and store the data in the data array
for (i = 0; i < 9; i++) {
data[i] = oneWire.read();
}
// Calculate the temperature in Celsius
int16_t raw = (data[1] << 8) | data[0];
float celsius = (float)raw / 16.0;
// Print the temperature to the serial monitor
Serial.print("Temperature: ");
Serial.print(celsius);
Serial.println(" C");
}
}
}
阅读全文