Simple ultrasonic sensor module HC-SR04 and 1602 LCD display were combined into useable digital yardstick.
Two versions of the sensor module from different suppliers worked similar way. The right one sometimes (name printed in the middle) had sometimes tendency to keep once entered “out of range” state forever. Simple transistor to switch on/off VCC did the trick – if the “out of range” state was longer than 1 second the module was switched off and switched on back.
The sensor is ooperated by standard Arduino commands, and the display is controlled by the object from LiquidCrystal_I2C library https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads/LiquidCrystal_V1.2.1.zip
The code:
#include <Wire.h> #include <LiquidCrystal_I2C.h> LiquidCrystal_I2C lcd(0x27,16,2); // set the LCD address to 0x27 for a 16 chars and 2 line display int Trig = 2; // Numer pinu wyzwolenia int Echo = 3; // Numer pinu odpowiedzi long EchoTime; // Czas trwania sygnału ECHO long OldEcho; // Poprzedni wynik pomiaru int Distance; // Odległość w centymetrach int MaximumRange = 300; // Maksymalna odległość (teoretycznie 400) int MinimumRange = 2; // Minimalna odległość void setup() { OldEcho = 0; lcd.init(); lcd.backlight(); pinMode(Trig, OUTPUT); pinMode(Echo, INPUT); } void loop() { delay(100); digitalWrite(Trig, LOW); // co najmniej dwie us stanu LOW powinny poprzedzać start pomiaru delayMicroseconds(2); digitalWrite(Trig, HIGH); // a teraz 10us wysokiego delayMicroseconds(10); digitalWrite(Trig, LOW); // i znowu niski - rozpoczyna się pomiar EchoTime = pulseIn(Echo, HIGH); // czas trwania stanu wysokiego na Echo Distance = EchoTime / 58; // przeliczona na cm if (Distance >= MaximumRange || Distance <= MinimumRange) { lcd.setCursor(0,0); lcd.print("Poza zakresem !"); lcd.setCursor(0,1); lcd.print("------:"); lcd.print(EchoTime,DEC); OldEcho = 0; } else { if (EchoTime > OldEcho + 25 || EchoTime < OldEcho - 25) { if (OldEcho == 0) lcd.clear(); // tylko gdy poprzedni niedobry, żeby nie migać OldEcho = EchoTime; lcd.setCursor(0,0); lcd.print("Odleglosc: "); lcd.setCursor(0,1); lcd.print(Distance, DEC); lcd.print(" cm "); } } }
One thought on “HC-SR04 and 1602”