#include <Wire.h> // I2C通信库
#include <LiquidCrystal_I2C.h> // 1602 LCD I2C库
// 初始化1602 LCD,设置I2C地址为0x27,16列2行
LiquidCrystal_I2C lcd(0x27, 16, 2);
#define TrigPin 9 // 超声波Trig引脚连接到数字引脚9
#define EchoPin 10 // 超声波Echo引脚连接到数字引脚10
void setup() {
pinMode(TrigPin, OUTPUT); // 设置Trig引脚为输出
pinMode(EchoPin, INPUT); // 设置Echo引脚为输入
lcd.init(); // 初始化LCD
lcd.backlight(); // 打开LCD背光
lcd.setCursor(0, 0); // 设置光标位置
lcd.print("Distance: "); // 显示标题
}
void loop() {
// 发送超声波脉冲
digitalWrite(TrigPin, LOW);
delayMicroseconds(2);
digitalWrite(TrigPin, HIGH);
delayMicroseconds(10);
digitalWrite(TrigPin, LOW);
// 读取回波时间(单位:微秒)
long duration = pulseIn(EchoPin, HIGH);
// 计算距离(单位:厘米)
float distance = duration * 0.034 / 2;
// 显示距离到LCD
lcd.setCursor(0, 1); // 设置光标到第二行
lcd.print(distance); // 显示距离
lcd.print(" cm"); // 显示单位
delay(500); // 每500ms更新一次
}