#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is connected to GPIO 4
#define ONE_WIRE_BUS 4
// 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(115200);
// Start the DS18B20 sensor
sensors.begin();
}
void loop() {
// Request temperature readings
sensors.requestTemperatures();
// Fetch and print temperature in Celsius
float temperatureC = sensors.getTempCByIndex(0);
// Check if the reading is valid
if (temperatureC != DEVICE_DISCONNECTED_C)
{
Serial.print("Temperature: ");
Serial.print(temperatureC);
Serial.println(" °C");
} else
{
Serial.println("Error: Could not read temperature data");
}
// Wait 1 second before the next reading
delay(1000);
}