#include <OneWire.h>
#include <DallasTemperature.h>
#include <LiquidCrystal.h>
// 定义数据引脚
#define ONE_WIRE_BUS 2
// 创建 OneWire 对象
OneWire oneWire(ONE_WIRE_BUS);
// 创建 DallasTemperature 对象
DallasTemperature sensors(&oneWire);
// Create LCD object (RS, EN, D4, D5, D6, D7)
LiquidCrystal lcd(7, 6, 5, 4, 3, 8); // Change pin numbers as per your wiring
void setup() {
// 初始化串口
Serial.begin(9600);
// 启动 DS18B20 传感器
sensors.begin();
// Initialize the LCD
lcd.begin(16, 2); // 16 columns and 2 rows
lcd.setCursor(0, 0);
lcd.print("Reading Temp...");
}
void loop() {
// 请求温度数据
sensors.requestTemperatures();
/*
// 读取温度(摄氏度)
float temperatureC = sensors.getTempCByIndex(0);
// 检查温度是否读取成功
if (temperatureC == DEVICE_DISCONNECTED_C) {
Serial.println("Error: 无法读取温度数据!");
} else {
Serial.print("当前温度: ");
Serial.print(temperatureC);
Serial.println(" °C");
}
*/
// 读取温度(摄氏度)
float tempC = sensors.getTempCByIndex(0);
// Check if reading is valid
if (tempC != DEVICE_DISCONNECTED_C) {
// Print the temperature on the LCD and Serial Monitor
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(tempC);
lcd.print(" C");
Serial.print("Temperature: ");
Serial.print(tempC);
Serial.println(" °C");
} else {
// Handle error if sensor is disconnected
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Sensor Error");
Serial.println("Error: Could not read from the sensor");
}
// 延时 1 秒
delay(1000);
}