#include <SoftwareSerial.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
const int trigPin = 6;
const int echoPin = 7;
LiquidCrystal_I2C lcd(0x27, 16, 2); // Adjust the I2C address if needed
// defines variables
long duration;
int distance;
SoftwareSerial mySerial(10, 11); // RX, TX
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.println("Goodnight moon!");
// set the data rate for the SoftwareSerial port
mySerial.begin(9600);
mySerial.println("Hello, world?");
// initialize the LCD
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Distance:");
}
void loop() { // run over and over
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state 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;
// Display distance on Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
// Send distance to the other device via SoftwareSerial
mySerial.print(String(distance) + ';');
// Display distance on LCD
lcd.setCursor(0, 1);
lcd.print(" "); // Clear the previous value
lcd.setCursor(0, 1);
lcd.print(distance);
lcd.print(" cm");
delay(500);
}