#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define TRIGGER_PIN 7 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 6 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
// Define LCD parameters
#define LCD_ADDRESS 0x27 // I2C address of your LCD module
#define LCD_COLS 16 // Number of columns your LCD has
// Initialize Ultrasonic sensor
long duration;
int distance;
void setup() {
Wire.begin();
Serial.begin(9600);
}
void loop() {
// Read distance from Ultrasonic sensor
distance = getDistance();
// Display the distance as a bargraph on LCD
displayBarGraph(distance);
delay(500); // Wait for a short duration before taking another measurement
}
int getDistance() {
// Send pulse to trigger ultrasonic sensor
pinMode(TRIGGER_PIN, OUTPUT);
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
// Read pulse from echo pin
pinMode(ECHO_PIN, INPUT);
duration = pulseIn(ECHO_PIN, HIGH);
// Calculate distance based on the duration of the pulse
int distance = duration * 0.034 / 2; // Divide by 2 because the pulse traveled to the object and back
return distance;
}
void displayBarGraph(int distance) {
Wire.beginTransmission(LCD_ADDRESS);
Wire.write(0x80); // Set cursor to the first column of the first row
// Calculate the number of bars to display based on distance
int numBars = map(distance, 0, MAX_DISTANCE, 0, LCD_COLS);
// Display the progression bar
for (int i = 0; i < LCD_COLS; i++) {
if (i < numBars) {
Wire.write('#'); // Display a filled bar
} else {
Wire.write(' '); // Display a space
}
}
Wire.endTransmission();
}