代码
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,16,2);
unsigned int EchoPin = 2;
unsigned int TrigPin = 3;
unsigned long Time_Echo_us = 0;
unsigned long Len_mm_X100 = 0;
unsigned long Len_Integer = 0;
unsigned int Len_Fraction = 0;
void distance()
{
digitalWrite(TrigPin, HIGH);
delayMicroseconds(50);
digitalWrite(TrigPin, LOW);
Time_Echo_us = pulseIn(EchoPin, HIGH);
if((Time_Echo_us < 60000) && (Time_Echo_us > 1))
{
Len_mm_X100 = (Time_Echo_us*34)/2;
Len_Integer = Len_mm_X100/100;
Len_Fraction = Len_mm_X100%100;
}
}
void setup(){
lcd.init();
lcd.backlight();
Serial.begin(9600);
pinMode(EchoPin, INPUT);
pinMode(TrigPin, OUTPUT);
}
void loop(){
distance();
lcd.init();
lcd.setCursor(0,0);
lcd.print("distance:");
lcd.print(Len_Integer);
lcd.print("mm");
lcd.setCursor(0,1);
lcd.print("Ture!");
delay(1000);
}