#include
#include "LiquidCrystal_attiny.h"
LiquidCrystal_I2C lcd(0x27,16,2);
const int TrigPin = 3;
const int EchoPin = 1;
float cm;
int n = 0;
void setup() {
lcd.init();
lcd.backlight();
lcd.home ();
lcd.print("SR04 RULER ");
pinMode(TrigPin, OUTPUT);
pinMode(EchoPin, INPUT);
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(TrigPin, LOW);
delayMicroseconds(2);
digitalWrite(TrigPin, HIGH);
delayMicroseconds(10);
digitalWrite(TrigPin, LOW);
cm = pulseIn(EchoPin, HIGH) / 58.0; //算成厘米
cm = (int(cm * 100.0)) / 100.0; //保留两位小数
if(cm > 10 && cm < 100)
n = 2;
if(cm < 100)
n = 1;
if(cm < 10 && n == 1)
{
// lcd,clear();
lcd.setCursor (4, 1 );
lcd.print(" ");
n = 0;
}
if(cm < 100 && n == 2)
{
//lcd.clear();
lcd.setCursor (5, 1 );
lcd.print(" ");
n = 0;
}
lcd.setCursor ( 0, 1 );
lcd.print(cm);
lcd.setCursor (9, 1 );
lcd.print("cm");
delay(1000);
}