#define PIN_TRIG 6
#define PIN_ECHO 7
#define led1 8
#define led2 9
#define led3 10
#define led4 11
#define led5 12
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
Serial.begin(9600);
pinMode(PIN_TRIG, OUTPUT);
pinMode(PIN_ECHO, INPUT);
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
pinMode(led4, OUTPUT);
pinMode(led5, OUTPUT);
lcd.init();
lcd.backlight();
lcd.print("Rachaporn");
lcd.setCursor(0, 1);
lcd.print("Distance:");
lcd.setCursor(0, 2);
}
void loop() {
int distanceCM;
digitalWrite( PIN_TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(PIN_TRIG, LOW);
distanceCM = pulseIn(PIN_ECHO, HIGH)/58.4;
Serial.print("Distance in CM: ");
Serial.println(distanceCM);
lcd.setCursor(0, 1);
lcd.print("Distance:");
lcd.println(distanceCM);
lcd.setCursor(13, 1);
lcd.print("cm");
delay(1000);
if ( distanceCM > 10.9 && distanceCM <100.9 )
{
digitalWrite(led1, 1);
digitalWrite(led2, 0);
digitalWrite(led3, 0);
digitalWrite(led4, 0);
digitalWrite(led5, 0);
}
else if( distanceCM > 110.9 && distanceCM <250.9 )
{
digitalWrite(led1, 0);
digitalWrite(led2, 1);
digitalWrite(led3, 0);
digitalWrite(led4, 0);
digitalWrite(led5, 0);
}
else if( distanceCM > 251.9 && distanceCM <300.9 )
{
digitalWrite(led1, 0);
digitalWrite(led2, 0);
digitalWrite(led3, 1);
digitalWrite(led4, 0);
digitalWrite(led5, 0);
}
else if(distanceCM > 301.9 && distanceCM <350.9 )
{
digitalWrite(led1, 0);
digitalWrite(led2, 0);
digitalWrite(led3, 0);
digitalWrite(led4, 1);
digitalWrite(led5, 0);
}
else if( distanceCM > 351.9 && distanceCM <400 )
{
digitalWrite(led1, 0);
digitalWrite(led2, 0);
digitalWrite(led3, 0);
digitalWrite(led4, 0);
digitalWrite(led5, 1);
}
}