#include <Wire.h>
#include <LiquidCrystal_I2C.h>
const int echopin = 2;
const int trigpin = 3;
const int led = 9;
long duration;
int distance;
LiquidCrystal_I2C lcd(0x27,16,2);
void setup(){
pinMode(trigpin, OUTPUT);
pinMode(echopin, INPUT);
pinMode(led, OUTPUT);
Serial.begin(9600);
digitalWrite(led, HIGH);
lcd.init();
lcd.backlight();
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Copyright @ ");
lcd.setCursor(0, 1);
lcd.print("Thanh 11A(0+1)");
delay(1200);
digitalWrite(led, LOW);
}
void loop(){
digitalWrite(trigpin, LOW);
delayMicroseconds(2);
digitalWrite(trigpin, HIGH);
delayMicroseconds(10);
digitalWrite(trigpin, LOW);
duration = pulseIn(echopin, HIGH);
distance = duration * 0.0340 / 2;
lcd.setCursor(0,0);
Serial.println(distance);
lcd.print("Distance: ");
lcd.print(distance);
lcd.print(" cm");
if (distance<=50){
digitalWrite(led, HIGH);
} else {
digitalWrite(led, LOW);
}
delay(500);
}