const int trigPin = 9;
const int echoPin = 10;
long duration; //Duration of Ping echo
int distance; //Distance calculation from duration measurement
int proximityTrig = 200; //Proximity trigger distance [cm]
#include <LiquidCrystal_I2C.h>
#define I2C_ADDR 0x27
#define LCD_COLUMNS 16
#define LCD_LINES 2
LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_LINES);
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT);
lcd.init();
lcd.backlight();
lcd.setCursor(2,0); //
lcd.print("Initialising");
lcd.setCursor(0,1); //second line, first column
int initDelay = 100; //time delay for the "*" symbols
for (int i = 0; i <=16; i++) { //loops to print "-" 16 times on the second line
lcd.print("*");
delay(initDelay);
}
delay(1000);
}
void loop() {
//Clears the LCD
lcd.clear();
//Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
//Sets trigPin HIGH for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
//Read the echoPin
duration = pulseIn(echoPin, HIGH);
//Calculates the distance
distance = duration*0.034/2;
//Print to serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Set LED to HIGH if distance < trigger value
if (distance <= proximityTrig){
digitalWrite(LED_BUILTIN, HIGH);
} else { //else set LED to LOW
digitalWrite(LED_BUILTIN,LOW);
}
//Print distance to LCD
lcd.print("Distance: ");
lcd.print(distance);
lcd.print(" cm");
delay(1000);
}