#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is connected to digital pin 2
const int oneWireBus = 2;
// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(oneWireBus);
// Pass oneWire reference to Dallas Temperature Sensor
DallasTemperature sensors(&oneWire);
void setup() {
// Start serial communication
Serial.begin(9600);
// Initialize the DS18B20 temperature sensor
sensors.begin();
}
void loop() {
// Request temperature data from all DS18B20 sensors on the bus
sensors.requestTemperatures();
// Get temperature in Celsius from the first DS18B20 sensor
// Why "byIndex"? You can have more than one IC on the same bus.
// 0 refers to the first IC on the wire
float temperatureCelsius = sensors.getTempCByIndex(0);
if (temperatureCelsius != DEVICE_DISCONNECTED_C) {
// Print the temperature to the serial monitor
Serial.print("Temperature: ");
Serial.print(temperatureCelsius);
Serial.println(" °C");
} else {
Serial.println("Error: Could not read temperature data.");
}
// Delay for a while before reading again
delay(1000);
}
Loading
ds18b20
ds18b20