// LCD I²C library
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,16,2); // creation of lcd instance with address, #characters, #lines
#include <SoftwareSerial.h>
int distance = 0;
int pinRX = 10;
int pinTX = 11;
unsigned char data_buffer[4] = {0};
unsigned char CS;
// Object to represent software serial port
SoftwareSerial mySerial(pinRX, pinTX);
void setup() {
// put your setup code here, to run once:
Serial.begin (9600);
// Set up SoftwareSerial port
mySerial.begin(9600);
}
void loop() {
// Check if data available on mySerial port
if (mySerial.available() > 0) {
delay (4);
if (mySerial.read() == 0xff) { // detect 0xff (= delimiter) before reading the 4 data bytes
data_buffer[0] = 0xff;
for (int i = 1; i < 4; i++) { // Read 4 data bytes
data_buffer[i] = mySerial.read();
}
// compute CheckSum
CS = data_buffer[0] + data_buffer[1] + data_buffer[2];
if (data_buffer[3] == CS) {
distance = (data_buffer[1] << 8) + data_buffer[2];
}
}
}
if (distance >= 4000 || distance <= 30) {
Serial.println("OutOfRange");
}
else {
// Serial.print (Dip1); Serial.print (Dip2);
Serial.print (distance);
Serial.println (" mm");
}
delay(2000);
}