#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is connected to 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 DS18B20 sensor
sensors.begin();
}
void loop() {
// Call sensors.requestTemperatures() to issue a global temperature request
sensors.requestTemperatures();
// Get temperature from DS18B20 sensor in Celsius
float temperatureC = sensors.getTempCByIndex(0);
// Check if temperature reading is valid
if (temperatureC != DEVICE_DISCONNECTED_C) {
// Print temperature to Serial Monitor
Serial.print("Temperature: ");
Serial.print(temperatureC);
Serial.println(" °C");
} else {
// Print an error message if temperature reading is invalid
Serial.println("Error: Unable to read temperature data");
}
delay(1000); // Delay for 1 second before next reading
}
/*Here's how the code works:
We include the OneWire and DallasTemperature libraries which are required to interface with the DS18B20 sensor.
We define the data wire connected to digital pin 2 as ONE_WIRE_BUS.
We create a OneWire instance called oneWire to communicate with the DS18B20 sensor.
We pass the oneWire reference to a DallasTemperature instance called sensors.
In the setup() function, we initialize serial communication and call sensors.begin() to initialize the DS18B20 sensor.
In the loop() function:
We call sensors.requestTemperatures() to request temperature data from the DS18B20 sensor.
We retrieve the temperature value in Celsius using sensors.getTempCByIndex(0).
We check if the temperature reading is valid (not equal to DEVICE_DISCONNECTED_C), and if so, we print the temperature to the Serial Monitor.
If the temperature reading is invalid, we print an error message.
We delay for 1 second before the next temperature reading.
Make sure you have the DS18B20 sensor connected properly to the Arduino Uno. The DS18B20's data pin should be connected to digital pin 2 on the Arduino, and the sensor should be powered according to its specifications.*/