#include <Wire.h>
#include <LiquidCrystal_I2C.h> //First instal the library: https://github.com/fdebrabander/Arduino-LiquidCrystal-I2C-library
// Set the LCD address.
//if you don't know what is your lcd address.
//just upload lcd I2C addressFinder code and check the serial moniter.
#define I2C_ADDR 0x27
#define LCD_COLUMNS 16
#define LCD_LINES 2
LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_LINES);
#define t1 20
const int trig = 2;
const int echo = 3;
int duration = 0;
int distance = 0;
void setup()
{
//LCD display
lcd.begin(16,2);
lcd.backlight();
Serial.begin(9600);
//ultrasonic sensor
pinMode(trig , OUTPUT);
pinMode(echo , INPUT);
//LEDS
for (int i = 4; i <= 13; i++) {
pinMode(i, OUTPUT);
}
}
void loop()
{
digitalWrite(trig , HIGH);
delayMicroseconds(1000);
digitalWrite(trig , LOW);
duration = pulseIn(echo , HIGH);
distance = (duration / 2) / 29.1 ;
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Distance: ");
lcd.print(distance);
if (distance <= 30) {
lcd.setCursor(0,1);
lcd.print("Distance is < 30");
delay(100);
effect_1();
}
else{
clear_led();
lcd.setCursor(0,1);
lcd.print("Distance is > 30");
delay(100);
}
}
//left to right and right to left
void effect_1()
{
for (int i = 4; i <= 13; i++) {
digitalWrite(i, HIGH);
delay(t1);
digitalWrite(i + 1, HIGH);
delay(t1);
digitalWrite(i + 2, HIGH);
delay(t1);
digitalWrite(i, LOW);
delay(t1);
digitalWrite(i + 1, LOW);
delay(t1);
}
for (int i = 13; i >= 4; i--) {
digitalWrite(i, HIGH);
delay(t1);
digitalWrite(i - 1, HIGH);
delay(t1);
digitalWrite(i - 2, HIGH);
delay(t1);
digitalWrite(i, LOW);
delay(t1);
digitalWrite(i - 1, LOW);
delay(t1);
}
}
// function to switch all LEDs off
void clear_led(void)
{
for (int i = 4; i <= 13; i++) {
digitalWrite(i, LOW);
}
}