Overview
In this project we are using HSR04 ultrasonic sensor module to measure distance by the time taken to reflect sound off an object and converting it to centimeters. The calculated distance will be displayed on a 20X4 LCD with an I2C backpack.
Components
Component Name | Purpose |
---|---|
Arduino Nano | This will be the microcontroller |
HCSR04 | This will be the ultrasonic sensor |
I2C LCD 20X4 | This will be the LCD display |
Circuit Diagram
Assembly
Nano Pin | HCSR04 Pin |
---|---|
D4 | Trig_pin |
D7 | Echo_pin |
5V | VCC |
GND | GND |
I2C LCD Pin
Nano Pin | I2C LCD Pin |
---|---|
A4 | SDA |
A5 | SCL |
5V | VCC |
GND | GND |
Code
/*
Project: ultrasonic sensor detection with output on LCD with I2C Backpack
Project Description:
This sketch writes distance readings read from the ultrasonic sensor sensor to an LCD display module.
This sketch is for a 20x4 screen.
Author: STEMVentor Educonsulting
This code is copyrighted. Please do not reuse or share for any purpose other than for learning with subscribed STEMVentor programs.
This code is for educational purposes only and is not for production use.
*/
// LIBRARIES
//used for communicating with I2C devices
#include <Wire.h>
//https://www.arduino.cc/reference/en/libraries/liquidcrystal-i2c/
// Install the LiquidCrystal I2C by Frank de Brabander from the IDE library manager.
#include <LiquidCrystal_I2C.h>
// PIN DEFINITIONS
// GLOBAL VARIABLES
// Define the display size
const byte rows = 4;
const byte cols = 20;
// Used for reading distance value.
float distanceValue;
// define the pin to which the ultrasonic sensor is connected to Arduino Nano
// comment these out if using Arduino Nano
#define trigPin 7
#define echoPin 4
// Un-comment these for pin defination if using ESP32
// #define trigPin 18
// #define echoPin 5
//define ultrasonic sensor speed in cm/uS
#define SOUND_SPEED 0.034
/* INITIALIZE OBJECTS
* Libraries usually follow an object-oriented approach that requires
* an instance of the class to call its methods.
*/
/*
* All I2C components have an address, the default is usually 0x27
* If that doesn't work, see this:https://playground.arduino.cc/Main/I2cScanner/
* The init statement accepts the address and the number of columns and rows.
*/
LiquidCrystal_I2C lcd(0x27, cols, rows);
/* LOCAL FUNCTIONS */
// Read sensor values
void readDistanceValue() //read HCSR-04 sensor value
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the ultrasonic sensor wave travel time in microseconds
long duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distanceValue = duration * SOUND_SPEED/2;
}
/*
Function to print to LCD on a single row.
Takes the row number and the text to display on that row (max 20 chars, rest will be truncated).
The entire display is cleared if the clear_all flag is true, else only the row is cleared (the default).
*/
void printToLCDByRow(int row, String text, bool clear_all = false)
{
const char* twenty_spaces = " ";
if(clear_all){
lcd.clear(); //clears the entire display
}
lcd.setCursor(0, row-1);
lcd.print(twenty_spaces); //clears the row
lcd.setCursor(0, row-1); //cursor has to be set again after printing spaces
lcd.print(text);
}
/*
Function to print to LCD across rows with each row having 20 chars.
Messages can be a maximum of 20x4 chars, rest will betruncated.
The entire display is cleared before printing the text.
Test string of 20 char:
12345678901234567890
Test strings of 80 chars:
12345678901234567890123456789012345678901234567890123456789012345678901234567890
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec varius est donec.
*/
void printToLCD(String text)
{
lcd.clear(); //clears the entire display
byte chars_remaining = text.length();
byte char_from = 0;
byte char_to = chars_remaining < cols ? text.length() : char_from + cols;
byte row = 1;
while(chars_remaining > 0){
String line = text.substring(char_from, char_to);
printToLCDByRow(row, line);
chars_remaining = text.length() - char_to;
char_from = char_to;
char_to = chars_remaining < cols ? text.length() : char_from + cols;
row++;
}
Serial.println("Data string has been displayed on LCD");
}
void LCD_setup() // function to LCD setup
{
// Initializing wire
Wire.begin();
// Initialize the LCD.
lcd.init();
// Turn on the blacklight and print a message.
lcd.backlight();
// Use the function to display text on each line indiviudally.
printToLCDByRow(1, "I2C LCD Ready!", true);
printToLCDByRow(2, "Enter some text.", false);
printToLCDByRow(3, "Max 80 characters.", false);
printToLCDByRow(4, "For a 20x4 LCD.", false);
delay(1000);
printToLCDByRow(1, "Measured distance: ", true);
}
void ultrasonicSetup() // function to setup HCSR-04 ultrasonic sensor setup
{
//Define the pinmode
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
}
/* SETUP CODE: runs once when the board starts up or resets */
void setup()
{
// Start the serial communication with baud rate suitable for your components.
Serial.begin(9600);
LCD_setup();
ultrasonicSetup();
Serial.println("The board is ready!");
}
/* MAIN LOOP: runs repeatedly at a very high frequency (1000s of times a second) */
void loop()
{
delay(1000);
readDistanceValue();
printToLCDByRow(2, String(distanceValue) + "cm", false);
}