Devices & Components
Arduino Uno Rev3
Breadboard (generic)
Ultrasonic Sensor - HC-SR04 (Generic)
Jumper wires (generic)
Rotary potentiometer (generic)
Standard LCD - 16x2 White on Blue
Project description
Code
Ultrasonic distance measurer with LCD display
arduino
1#include <LiquidCrystal.h> //Load Liquid Crystal Library 2LiquidCrystal LCD(12, 11, 5, 4, 3, 2); //Create Liquid Crystal Object called LCD 3 4int trigPin=9; //Sensor Trip pin connected to Arduino pin 9 5int echoPin=7; //Sensor Echo pin connected to Arduino pin 7 6int myCounter=0; //declare your variable myCounter and set to 0 7int servoControlPin=6; //Servo control line is connected to pin 6 8float pingTime; //time for ping to travel from the sensor to the target and return 9float targetDistance; //Distance to Target in Centimeters 10float speedOfSound=776.5; //Speed of sound in miles per hour 11 12void setup() { 13 14Serial.begin(9600); 15pinMode(trigPin, OUTPUT); 16pinMode(echoPin, INPUT); 17LCD.begin(16,2); //Tell Arduino to start your 16x2 LCD 18LCD.setCursor(0,0); //Set LCD cursor to upper left corner, column 0, row 0 19LCD.print("Distance:"); //Print Message on First Row 20} 21 22void loop() { 23 24 digitalWrite(trigPin, LOW); //Set trigger pin low 25 delayMicroseconds(2000); //Let signal settle 26 digitalWrite(trigPin, HIGH); //Set trigPin high 27 delayMicroseconds(15); //Delay in high state 28 digitalWrite(trigPin, LOW); //ping has now been sent 29 delayMicroseconds(10); //Delay in high state 30 31 pingTime = pulseIn(echoPin, HIGH); //pingTime in microceconds 32 pingTime=pingTime/1000000; //convert pingTime to seconds by dividing by 1000000 (microseconds in a second) 33 pingTime=pingTime/3600; //convert pingtime to hours by dividing by 3600 (seconds in an hour) 34 targetDistance= speedOfSound * pingTime; //This will be in miles, since we declared the speed of sound as kilometers per hour; although we're going to convert it back to centimeters 35 targetDistance=targetDistance/2; //Remember ping travels to the target and back from the target, so you must divide by 2 for actual target distance. 36 targetDistance= targetDistance*160934,4; //Convert miles to centimeters by multipling by 160934,4 37 38 39 40 LCD.setCursor(0,1); //Set the cursor to the first column of the second row 41 LCD.print(" "); //Print blanks to clear the row 42 LCD.setCursor(0,1); //Set Cursor again to the first column of the second row 43 LCD.print(targetDistance); //Print measured distance 44 LCD.print(" centimeters"); //Print your units 45 delay(250); //Pause to let things settle 46 47}
Downloadable files
Ultrasonic distance measurer with LCD display support
Tried to keep the Fritzing scheme as simple as possible
Ultrasonic distance measurer with LCD display support
Ultrasonic distance measurer with LCD display support
Tried to keep the Fritzing scheme as simple as possible
Ultrasonic distance measurer with LCD display support
Comments
Only logged in users can leave comments