Arduino Tutorial #22 Ultrasonic sensor counter with LCD display

Ultrasonic sensor counter with LCD display

In this tutorial we will see how to use ultrasonic sensor as a counter and output will be shown on LCD display. It will count number of times object passes in front of sensor. So let’s get started. For this you will need

  1. Arduino,
  2. Ultrasonic sensor,
  3. LCD display,
  4. Potentiometer (for adjusting contrast of LCD),
  5. Breadboard,
  6. 4.7 K ohms Resistor,
  7. Jumper wires.


 Ultrasonic sensor counter with LCD circuit diagram
Ultrasonic sensor counter with LCD circuit diagram


Do connection as shown in diagram. Provide separate ground for ultrasonic sensor. And connect VCC pin near to 5V pin. Otherwise it will not work and sensor will give constantly increment values even you are not doing anything with sensor.


Sketch for Ultrasonic sensor counter with LCD
 #include <LiquidCrystal.h>
 #define trigPin 13
 #define echoPin 8
 // initialize the library with the numbers of the interface pins
 LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
 int counter = 0;
 int currentState = 0;
 int previousState = 0;
 void setup() {
 pinMode(trigPin, OUTPUT);
 pinMode(echoPin, INPUT);
 lcd.begin(16, 2);
 lcd.setCursor(4, 0);
 void loop() {
 long duration, distance;
 digitalWrite(trigPin, LOW); 
 digitalWrite(trigPin, HIGH);
 digitalWrite(trigPin, LOW);
 duration = pulseIn(echoPin, HIGH);
 distance = (duration/2) / 29.1;
 if (distance <= 10){
 currentState = 1;
 else {
 currentState = 0;
 if(currentState != previousState){
 if(currentState == 1){
 counter = counter + 1;

This code is already explain in previous tutorial measuring distance with ultrasonic and ultrasonic as a counter. In this tutorial we have added LCD for output. Now let’s come to the programming part. Include liquid crystal library. Define trigger and echo pins. Initialize liquid crystal library. Define variables for detecting changes in state.  In setup function declare pin mode for trigger and echo pin. Set cursor at little bit right side and print counter text on LCD. In loop function this will determine the distance. If any object comes within range of 10 cm. current state will be equal to 1. If current state equal to 1 it will count 1. LCD cursor is set to second row for printing counting values.

You can see when I move box in front of ultrasonic sensor it counts how many time box passes.


LIST OF COMPONENT BUY ONLINE:   (Arduino) (LCD display)   (Ultrasonic sensor) (Potentiometer)  (Resistor)  (Breadboard)   (Jumper wire)