#include <LiquidCrystal_I2C.h>
// pin constants
const int TRIG_PIN = 27;
const int ECHO_PIN = 26;
int oldDistance = 0;
LiquidCrystal_I2C lcd(0x27, 20, 4);
long getDuration() {
// create trigger pulse
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// measure the duration of the pulse on the echo pin
long pulseLen = pulseIn(ECHO_PIN, HIGH);
return pulseLen;
}
void showSplash() {
lcd.setCursor(3, 1);
lcd.print("Distance Sensor");
lcd.setCursor(8, 2);
lcd.print("V1.0");
delay(2000);
lcd.clear();
}
void updateDisplay(int cm, int inches) {
char buffer[32];
snprintf(buffer, 32, "Distance: %3d cm %3d in.", cm, inches);
Serial.println(buffer);
snprintf(buffer, 16, "%3d cm", cm);
lcd.setCursor(4, 1);
lcd.print(buffer);
snprintf(buffer, 16, "%3d inches", inches);
lcd.setCursor(4, 3);
lcd.print(buffer);
}
void setup() {
Serial.begin(115200);
lcd.init();
lcd.backlight();
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
// show title page
showSplash();
// initialize LCD headers
lcd.setCursor(2, 0);
lcd.print("Dist: (SI units)");
lcd.setCursor(2, 2);
lcd.print("Dist: (Imperial)");
}
void loop() {
long duration = getDuration();
// calculate distances
int cmDistance = (int) (duration * 0.0341 / 2) + 0.5;
int inDistance = (int) (duration * 0.0134 / 2) + 0.5;
// update display if distance changed
if (cmDistance != oldDistance) {
oldDistance = cmDistance;
updateDisplay(cmDistance, inDistance);
}
// small delay between measurements
delay(100);
}