Code
#include <SoftwareSerial.h> #include "LCD.h" #include <LiquidCrystal_I2C.h> #define I2C_ADDR 0x27 // <<----- Add your address here. Find it from I2C Scanner #define BACKLIGHT_PIN 3 #define En_pin 2 #define Rw_pin 1 #define Rs_pin 0 #define D4_pin 4 #define D5_pin 5 #define D6_pin 6 #define D7_pin 7 LiquidCrystal_I2C lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin); SoftwareSerial sonarSerial(10, 11); // RX, TX - connect sensor TX to pin 10 void setup() { lcd.begin(20,4); lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE); lcd.setBacklight(HIGH); lcd.setCursor(0,0); lcd.setCursor(0,0); lcd.print("C.B.ELECTRONICS"); delay(500); lcd.setCursor(0,1); lcd.print("Lebanese Park"); delay(500); sonarSerial.begin(9600); // JSN-SR04T serial mode baud rate delay(1000); // Let the sensor boot lcd.clear(); } void loop() { // Send 0x55 command to request distance sonarSerial.write(0x55); // Wait for response (should be 4 bytes) delay(100); // wait for response if (sonarSerial.available() >= 4) { byte header = sonarSerial.read(); byte highByte = sonarSerial.read(); byte lowByte = sonarSerial.read(); byte checksum = sonarSerial.read(); float distance = (highByte << 8) | lowByte; //distance in mm byte calculatedChecksum = header + highByte + lowByte; lcd.clear(); lcd.setCursor(0,0); lcd.print("Distance: "); if (checksum == calculatedChecksum && header == 0xFF) { if(distance==6000) { lcd.clear(); lcd.setCursor(0,0); lcd.print("Out of Range, object"); lcd.setCursor(0,1); lcd.print("may be too close or"); lcd.setCursor(0,2); lcd.print("echo pulse may not"); lcd.setCursor(0,3); lcd.print("be returning cleanly"); } else{ lcd.print(distance/10); lcd.print(" cm"); lcd.setCursor(0,1); lcd.print("Distance: "); lcd.print(distance/1000); lcd.print(" m"); } } else { lcd.clear(); lcd.setCursor(0,0); lcd.print("Invalid data or checksum!"); lcd.setCursor(0,1); lcd.print("Will Try again"); lcd.setCursor(0,2); lcd.print("in 2 seconds"); } } delay(2000); // wait before next trigger }