#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define echoPin 18 // Attach pin D2 Arduino to pin Echo of HC-SR04
#define trigPin 5 // Attach pin D3 Arduino to pin Trig of HC-SR04
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Defines variables
long duration; // Variable for the duration of sound wave travel
int distance; // Variable for the distance measurement
void setup() {
Wire.begin();
lcd.begin(16, 2);
lcd.setCursor(0, 0);
lcd.print(" MONSTERCHIP");
lcd.setCursor(0, 1);
lcd.print(" badut");
delay(5000);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(" Ultrasonic");
pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
Serial.begin(115200);
}
void loop() {
// Clears the trigPin condition
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin HIGH (ACTIVE) for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
// Clear the distance display before printing the new distance
lcd.setCursor(9, 1);
lcd.print(" ");
lcd.setCursor(0, 1);
lcd.print("Distance: ");
lcd.setCursor(9, 1);
lcd.print(distance);
lcd.print(" cm ");
delay(500); // Add a small delay to make the display readable
}