/*
Project: "Ping" Distance Display
Description: Displays the distance measured
by an ultrasonic sensor on LCD
Creation date: 9/28/23
Author: AnonEngineering
License: https://en.wikipedia.org/wiki/Beerware
https://docs.arduino.cc/built-in-examples/sensors/Ping
*/
#include <LiquidCrystal.h>
// global constants
const int MIN_RANGE = 68; // minimum marker range in cm
const int MAX_RANGE = 70; // maximum marker range in cm
// pin constants
const int TRIG_PIN = 6;
const int ECHO_PIN = 5;
const int MODE_PIN = 4;
// create an LCD object - 'name' (RS, EN, D4, D5, D6, D7)
LiquidCrystal lcd(12, 11, 10, 9, 8, 7);
void setup() {
Serial.begin(9600); // initialize serial communications
lcd.begin(16, 2); // initialize 16 x 2 lcd screen
pinMode(MODE_PIN, INPUT_PULLUP); // metric / imperial switch
pinMode(TRIG_PIN, OUTPUT); // set trigger pin as an output
pinMode(ECHO_PIN, INPUT); // set echo pin as an input
//lcd.setCursor(0, 0); // (begin starts the display at 0, 0)
lcd.print("Target Distance: "); // print first row
}
void loop() {
char dispChars[16];
char distanceBuff[6];
char rangeBuff[6];
char scaleBuff[4];
float lcdDistance = 0.0;
float lowRange = 0.0;
float hiRange = 0.0;
// get the scale mode
bool mode = digitalRead(MODE_PIN);
// get the echo time
digitalWrite(TRIG_PIN, LOW); // make sure trigger is low
delayMicroseconds(5);
digitalWrite(TRIG_PIN, HIGH); //set trigger pin high
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW); // bring trigger pin back low
unsigned long pingTime = pulseIn(ECHO_PIN, HIGH); // wait for echo
// calculate distance (/2 for round trip)
// 34300 cm/s = 29.2us/cm
// 13503 in/s = 74.2us/in
float distanceCM = pingTime / 29.2 / 2;
float distanceIN = pingTime / 74.2 / 2;
// set the display distance, scale indicator, and ranges
if (mode) {
lcdDistance = distanceIN;
strncpy(scaleBuff, "in", 3);
lowRange = MIN_RANGE / 2.54;
hiRange = MAX_RANGE / 2.54;
} else {
lcdDistance = distanceCM;
strncpy(scaleBuff, "cm", 3);
lowRange = MIN_RANGE;
hiRange = MAX_RANGE;
}
// convert the float distance to a char array
dtostrf(lcdDistance, 4, 1, distanceBuff);
// set the range indicator
if (lcdDistance >= lowRange && lcdDistance <= hiRange) {
strncpy(rangeBuff, "Nice!", 6);
} else {
strncpy(rangeBuff, " ", 6);
}
// format all the data into a char array
sprintf(dispChars, " %s %s %s ", rangeBuff, distanceBuff, scaleBuff);
// print the formatted data to the LCD's bottom row
lcd.setCursor(0, 1);
lcd.print(dispChars);
}CM / IN