Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <Wire.h>
- #include <LiquidCrystal_I2C.h>
- // Define the pins for the ultrasonic sensor
- const int trigPin = 9;
- const int echoPin = 10;
- // Define variables for duration and distance
- long duration;
- int distance;
- // Initialize the LCD object with the address and dimensions of your LCD
- LiquidCrystal_I2C lcd(0x27, 16, 2);
- // Define LED pins
- const int ledLow = 11;
- const int ledMid = 12;
- const int ledHigh = 13;
- // Function declarations
- void initialize();
- void measureDistance();
- void displayDistance();
- void determineDistanceCategory();
- void turnOnLowLED();
- void turnOnMidLED();
- void turnOnHighLED();
- void setup() {
- initialize();
- }
- void loop() {
- measureDistance();
- displayDistance();
- determineDistanceCategory();
- delay(500);
- }
- void initialize() {
- // Initialize serial communication
- Serial.begin(9600);
- // Initialize LCD display
- lcd.init();
- lcd.backlight();
- lcd.setCursor(0,0);
- lcd.print("Distance: ");
- // Set LED pins as outputs
- pinMode(ledLow, OUTPUT);
- pinMode(ledMid, OUTPUT);
- pinMode(ledHigh, OUTPUT);
- // Set trigPin as an output and echoPin as an input
- pinMode(trigPin, OUTPUT);
- pinMode(echoPin, INPUT);
- }
- void measureDistance() {
- // Clear the trigPin
- digitalWrite(trigPin, LOW);
- delayMicroseconds(2);
- // Send a pulse to the trigPin
- digitalWrite(trigPin, HIGH);
- delayMicroseconds(10);
- digitalWrite(trigPin, LOW);
- // Measure the duration of the pulse on the echoPin
- duration = pulseIn(echoPin, HIGH);
- // Calculate the distance in centimeters
- distance = duration * 0.034 / 2;
- }
- void displayDistance() {
- // Print the distance to the Serial Monitor
- Serial.print("Distance: ");
- Serial.print(distance);
- Serial.println(" cm");
- // Display the distance on the LCD display
- lcd.setCursor(10,0);
- lcd.print(distance);
- lcd.print(" cm ");
- }
- void determineDistanceCategory() {
- // Clear the second row of the LCD display
- lcd.setCursor(0,1);
- lcd.print(" "); // Clear the row
- // Determine the distance category and display it on the LCD
- lcd.setCursor(0,1);
- if(distance < 20) {
- lcd.print("Low");
- turnOnLowLED();
- } else if(distance >= 20 && distance < 50) {
- lcd.print("Mid");
- turnOnMidLED();
- } else {
- lcd.print("High");
- turnOnHighLED();
- }
- }
- void turnOnLowLED() {
- digitalWrite(ledLow, HIGH);
- digitalWrite(ledMid, LOW);
- digitalWrite(ledHigh, LOW);
- }
- void turnOnMidLED() {
- digitalWrite(ledLow, LOW);
- digitalWrite(ledMid, HIGH);
- digitalWrite(ledHigh, LOW);
- }
- void turnOnHighLED() {
- digitalWrite(ledLow, LOW);
- digitalWrite(ledMid, LOW);
- digitalWrite(ledHigh, HIGH);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement