#include <LiquidCrystal.h> // 导入 LCD 库
#include <Servo.h> // 导入舵机库
// 定义温度传感器引脚
const int tempSensorPin = A0;
// 定义电位器引脚
const int potPin = A1;
// 定义按钮引脚
const int buttonPin = 2;
// 定义舵机引脚
const int servoPin = 3;
// 初始化 LCD
LiquidCrystal lcd(11,10, 4, 5, 6,7); // 初始化 LCD 对象并连接到相应引脚
// 初始化舵机
Servo servo;
// 显示温度的函数
void displayTemperature(float temperature, char unit) {
lcd.clear(); // 清空 LCD 屏幕
lcd.setCursor(0, 0); // 设置光标位置到第一行第一列
lcd.print("T: "); // 显示文本
lcd.print(temperature); // 显示温度值
lcd.print(" "); // 添加空格
lcd.print(unit); // 显示温度单位
}
void setup() {
// 初始化舵机
servo.attach(servoPin);
// 初始化按钮引脚
pinMode(buttonPin, INPUT_PULLUP);
// 初始化 LCD
lcd.begin(16, 2);
}
void loop() {
// 读取温度
int sensorValue = analogRead(tempSensorPin);//0~1023
// 模拟值转换为摄氏度
float temperatureC = (sensorValue / 1024.0) * 5 * 100.0;
// 读取电位器值并映射到舵机角度范围内
int potValue = analogRead(potPin);
int angle = map(potValue, 0, 1023, 0, 180);//转化成角度
servo.write(angle); // 舵机转动到指定角度
// 检查按钮状态
if (digitalRead(buttonPin) == LOW) { // 按钮按下
// 计算华氏温度
float temperatureF = (temperatureC * 9.0 / 5.0) + 32.0;
// 显示华氏温度
displayTemperature(temperatureF, 'F');
} else { // 按钮未按下
// 显示摄氏温度
displayTemperature(temperatureC, 'C');
}
// 延迟一段时间
delay(500);
}