//cslg单片机课程AD和I2C仿真实验案例
#include <LiquidCrystal_I2C.h>
// 定义I2C地址和LCD的行列数
#define I2C_ADDR 0x27
#define LCD_COLUMNS 16
#define LCD_LINES 2
LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_LINES);
// 变量定义
int buttonState; // 按钮状态
int x = 0; // 用于切换显示模式的计数器
const int buttonPin = 4; // 按钮连接的引脚
float resistance = 0; // 从模拟输入读取的电阻值
float pot = 0; // 转换后的电位器电压值
float volts = 0; // 暂时未使用的电压变量
float tempC = 0; // 摄氏温度
float tempF = 0; // 华氏温度
const int ledPin = 7; // LED连接的引脚
void setup() {
// 初始化串口通信
Serial.begin(9600);
// 设置引脚模式
pinMode(A0, INPUT); // 模拟输入A0用于读取温度传感器的值
pinMode(ledPin, OUTPUT); // 设置LED引脚为输出
pinMode(buttonPin, INPUT); // 设置按钮引脚为输入
// 初始化LCD显示
lcd.init();
lcd.backlight();
}
void loop() {
// 读取模拟输入,计算温度
resistance = analogRead(A0);
pot = resistance * 5.0 / 1023.0; // 将模拟值转换为电压
tempC = pot / 0.01; // 根据传感器特性计算摄氏温度
tempF = tempC * 1.8 + 32; // 转换为华氏温度
// 读取按钮状态
buttonState = digitalRead(buttonPin);
// 根据按钮点击次数切换显示模式
if (buttonState == HIGH) {
x++;
delay(250); // 防抖延时
if (x >= 2) {
x = 0; // 重置计数器
}
}
// 根据x的值决定显示摄氏或华氏温度
if (x == 0) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Temperatura:");
lcd.setCursor(0, 1);
lcd.print("Graus C:");
lcd.setCursor(9, 1);
lcd.print(tempC);
delay(500);
} else if (x == 1) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Temperatura:");
lcd.setCursor(0, 1);
lcd.print("Graus F:");
lcd.setCursor(9, 1);
lcd.print(tempF);
delay(500);
}
// 根据温度控制LED
if (tempC >= 30) {
digitalWrite(ledPin, HIGH); // 温度高于30度,LED亮
delay(200);
}
if (tempC <= 25) {
digitalWrite(ledPin, LOW); // 温度低于25度,LED灭
delay(250);
}
}