Matt McNamara
Published

Measure Distance!

Measure distance using an ultrasonic sensor and display values on a serial LCD display.

BeginnerFull instructions provided1 hour1,529
Measure Distance!

Things used in this project

Hardware components

Arduino UNO
Arduino UNO
×1
RGB LCD Shield Kit, 16x2 Character Display
RGB LCD Shield Kit, 16x2 Character Display
×1
Grove - Ultrasonic Ranger
Seeed Studio Grove - Ultrasonic Ranger
×1

Software apps and online services

Arduino IDE
Arduino IDE

Story

Read more

Schematics

Schematic

Code

ultrasonic.lcd.c

C/C++
#include <Ultrasonic.h>
#include <Wire.h> 
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27,20,4);  // set the LCD address to 0x27 for a 16 chars and 2 line display
Ultrasonic ultrasonic(7);          // Connect to Pin 7 on UNO

void setup()
    {
    Serial.begin(9600);              // set the serial port to 9600 baud for debugging
    lcd.init();                      // initialize the lcd 
    lcd.backlight();                 // turn on the backlight
    lcd.clear();                     // clear the screen
    }

void loop()
    {
    long RangeInInches;
    long RangeInCentimeters;

    lcd.clear();                                      // clear the screen  
    lcd.setCursor(1,0);                               // set the position to column 1, line 0
    lcd.print("ULTRASONIC SENSOR");
    Serial.print("The distance to obstacles in front is: ");
    RangeInInches = ultrasonic.MeasureInInches();     // obtain the distance in inches
    lcd.setCursor(0,1);                               // set the positiom to column 0, line 1
    lcd.print(RangeInInches);                         // display the value on the LCD
    lcd.setCursor(3,1);                               // set the position to column 3, line 1
    lcd.print(" inch");
    Serial.print(RangeInInches);                      // 0~157 inches
    Serial.print(" inch ");
    
    RangeInCentimeters = ultrasonic.MeasureInCentimeters(); // obtain distance in centimeters
    Serial.print(RangeInCentimeters);                       // 0~400cm
    lcd.setCursor(0,2);                                     // set the position to column 0, line 2
    lcd.print(RangeInCentimeters);                          // obtain the distance in centimeters
    lcd.setCursor(3,2);                                     // set the position to column 3, line 2
    lcd.print(" cm");
    
    Serial.println(" cm");
    delay(250);                                             // delay 250ms 
    }

Credits

Matt McNamara

Matt McNamara

2 projects • 1 follower

Comments