////////////////////////////////////////////////////////////////////
// Author: RSP @KMUTNB
// Date: 2022-02-08
// File: nano_ultrasonic_lcd_i2c_demo.ino
////////////////////////////////////////////////////////////////////
#include <Wire.h>
// Add the LCD_I2C library for Arduino
#include <LCD_I2C.h> // see: https://github.com/blackhack/LCD_I2C
// see also: https://docs.wokwi.com/parts/wokwi-hc-sr04
#define TRIG_PIN (5) // Arduino pin for the TRIG signal
#define ECHO_PIN (2) // Arduino pin for the ECHO signal
#define TIMEOUT_USEC (30000) // timeout in usec
#define SOUND_SPEED (343) // in msec per sec
#define USEC_TO_CM(x) ((SOUND_SPEED*100UL)*(x)/1000000)
// use the default address of most PCF8574_LCD16x2 module
// create a LCD_I2C object:
// I2C address, no. of characters per line and no. of lines
LCD_I2C lcd( 0x27, 16, 2 );
void setup() {
Serial.begin( 115200 ); // set baudrate to 115200
pinMode( ECHO_PIN, INPUT_PULLUP ); // set ECHO pin as output
pinMode( TRIG_PIN, OUTPUT ); // set TRIG pin as input
digitalWrite( TRIG_PIN, LOW ); // output LOW to TRIG pin
lcd.begin(); // initialize the LCD screen
lcd.backlight(); // turn on the LCD backlight
}
char sbuf[2][20]; // string buffer for two text lines of 20 chars max.
void loop() {
// Step 1) send a short pulse (e.g. 20 usec) on TRIGGER pin.
digitalWrite( TRIG_PIN, HIGH );
delayMicroseconds(20);
digitalWrite( TRIG_PIN, LOW );
// Step 2) busy-wait to read the pulse width of the signal
// on the ECHO pin with timeout (30 msec max.).
uint32_t pw = pulseIn( ECHO_PIN, HIGH, TIMEOUT_USEC );
// Step 3) compute the distance from the obstacle
uint16_t distance_cm = USEC_TO_CM(pw/2);
// Step 4) prepare output strings
sprintf( sbuf[0], " Echo: %5u us", pw );
sprintf( sbuf[1], "Range: %5u cm", distance_cm );
// Step 5) send text messages to the LCD screen
lcd.clear(); // clear LCD screen
lcd.setCursor(0,0); // goto the begin of the first line
lcd.print( sbuf[0] ); // write the first line to LCD screen
lcd.setCursor(0,1); // goto the begin of the second line
lcd.print( sbuf[1] ); // write the second line to LCD screen
// Step 6) send text messages to Serial
Serial.println( sbuf[0] ); // send the first text line
Serial.println( sbuf[1] ); // send the second text line
delay(200);
}
////////////////////////////////////////////////////////////////////