I am trying to use US-100 sensor to measure distance but it gets wrong reading (first reading only) in loop.
My main sketch is for water level monitor / control with EEPROM (pump states in case of power failure). Due to this wrong reading it get trip in loop after startup. When I check the sensor reading separately I observed first reading is wrong and due to this pump trip.
Can any one point out the problem or any solution.
#include <SoftwareSerial.h>;
#include <LiquidCrystal_I2C.h> //addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
const int US100_TX = 11;
const int US100_RX = 12;
SoftwareSerial US100Serial(US100_RX, US100_TX);
unsigned int MSByteDist = 0;
unsigned int LSByteDist = 0;
unsigned int mmDist = 0;
int temp = 0;
void setup() {
Serial.begin(9600);
lcd.begin(16, 2);
US100Serial.begin(9600);
}
void loop() {
US100Serial.flush();
US100Serial.write(0x55);
delay(500);
if (US100Serial.available() >= 2)
{
MSByteDist = US100Serial.read();
LSByteDist = US100Serial.read();
mmDist = MSByteDist * 256 + LSByteDist;
if ((mmDist > 1) && (mmDist < 10000))
{
Serial.print("Distance: ");
Serial.print(mmDist, DEC);
Serial.println(" mm");
lcd.setCursor(0, 0);
lcd.print("Distance: ");
lcd.print(mmDist, DEC);
lcd.print(" ");
}
}
US100Serial.flush();
US100Serial.write(0x50);
delay(50);
if (US100Serial.available() >= 1)
{
temp = US100Serial.read();
if ((temp > 1) && (temp < 130)) // temprature is in range
{
temp -= 45; // correct 45º offset
Serial.print("Temp: ");
Serial.print(temp, DEC);
Serial.println(" ºC.");
lcd.setCursor(1, 1);
lcd.print(" Temp: ");
lcd.print(temp, DEC);
lcd.print(" ºC.");
}
}
delay(500);
}
Serial out put is like: (only first reading wrong)
Distance: 280 mm
Temp: 27 ºC.
Distance: 200 mm
Temp: 27 ºC.
Distance: 201 mm
Temp: 27 ºC.
Distance: 200 mm
Temp: 27 ºC.