#include <OneWire.h>
#include <DallasTemperature.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Initialize 16x4 LCD (I2C address may vary)
LiquidCrystal_I2C lcd(0x27, 16, 4); // Adjust address to 0x3F if needed
// Data wire for DS18B20
#define ONE_WIRE_BUS 2
// Setup oneWire instance
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
DeviceAddress tempSensor;
void setup() {
Serial.begin(9600);
// Initialize LCD
lcd.init();
lcd.backlight();
lcd.clear();
// Start DS18B20 sensor
sensors.begin();
// Check for temperature sensors
if (!sensors.getDeviceCount()) {
lcdPrintError("No sensor found!");
while(1);
}
// Configure sensor resolution
sensors.getAddress(tempSensor, 0);
sensors.setResolution(tempSensor, 12);
// Display header
lcd.setCursor(0, 0);
lcd.print("Digital Thermometer");
lcd.setCursor(0, 1);
lcd.print("----------------");
}
void loop() {
sensors.requestTemperatures();
float tempC = sensors.getTempC(tempSensor);
// Check if reading is valid
if(tempC == DEVICE_DISCONNECTED_C) {
lcdPrintError("Sensor Error!");
return;
}
updateDisplay(tempC);
delay(1000);
}
void updateDisplay(float celsius) {
float fahrenheit = (celsius * 9.0 / 5.0) + 32;
// Clear previous temperature values
lcd.setCursor(0, 2);
lcd.print(" ");
lcd.setCursor(0, 3);
lcd.print(" ");
// Display Celsius
lcd.setCursor(3, 2);
lcd.print(celsius, 1);
lcd.write(223); // Degree symbol
lcd.print("C");
// Display Fahrenheit
lcd.setCursor(3, 3);
lcd.print(fahrenheit, 1);
lcd.write(223);
lcd.print("F");
// Serial monitor output
Serial.print("Temperature: ");
Serial.print(celsius, 1);
Serial.print("°C / ");
Serial.print(fahrenheit, 1);
Serial.println("°F");
}
void lcdPrintError(const char *msg) {
lcd.clear();
lcd.setCursor(0, 1);
lcd.print(msg);
}