#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is plugged into digital pin 2 on the Arduino
#define ONE_WIRE_BUS 2
// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature sensor
DallasTemperature sensors(&oneWire);
void setup() {
// Start serial communication
Serial.begin(9600);
// Initialize the DallasTemperature library
sensors.begin();
}
void loop() {
// Request temperatures from all devices on the bus
sensors.requestTemperatures();
// Get temperature in Celsius
float temperatureC = sensors.getTempCByIndex(0);
// Check if temperature reading is valid
if (temperatureC != DEVICE_DISCONNECTED_C) {
// Print the temperature to Serial Monitor
Serial.print("Temperature: ");
Serial.print(temperatureC);
Serial.println(" °C");
} else {
// If reading failed, print an error message
Serial.println("Error: Unable to read temperature.");
}
// Wait for a short delay before reading again
delay(1000);
}