Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

let's make

Explore(/tag/typeid/)

Publish(/about/create.jsp)

Classes(/classes/)
Featured: share what you make(/halloween/) (/halloween/)
(/id/intel/) IntelIoT(/id/intel/)
(/)
(/tag/typeid/categorytechnology/channelleds/) LEDs(/tag/typeid/categorytechnology/channelleds/)
(/tag/typeid/categorycostumes/) Costumes(/tag/typeid/categorycostumes/)

UltrasonicdistancemeterwithLCDdisplayonArduinoUNO by
techrm(/member/techrm/)insensors(/tag/typeid/categorytechnology/channelsensors/)
Download

h(/id/UltrasonicdistancemeterwithLCDdisplayonArdu/)

4Steps

Collection

IMadeit!

Favorite

Share

Ultrasonic distance meter with LCD display on Arduino UNO

AboutThisInstructable

8 23,697 views
265 favorites
InthistutorialwearegoingtoseeadifferentuseoftheHCSR04ultrasonic
module.Thismoduleisoftenusedonrobotsandtoycarstolocateobstaclesbut
itcanbeusedtomeasuredistancesaswell.
DistancesmeasuredbytheHCSR04willbeshownonourbelovedLCD16x2
display.Takealookatourtutorialifyouwanttoknowhowtosolderapinheader
tothiskindofdisplay.(http://www.instructables.com/id/Yetanothertutorialon
howtosolder/)

techrm
(/member/techrm/)
TechRM'swebsite
(http://techrm.blogspot.it/)

(/member/techrm/)
Follow

103

Morebytechrm:

ThemaximumrangeofHCSR04is4meters,andtheshortestmeasurable
distanceis2cmwithanaccuracyof3mm.Wemadeapiezoelectricspeakerring
whenthedistancemetersgoesoutofreach.
Othertwothingsarerequiredifyouwantyourdistancemetertodomore
accuratemeasurements:

License:

(/id/ASimple

HydroponicSystemWithMediaTekLinkIt

1.Aspiritlevel
2.Alaserpointer
Unfortunately,whilemakingtestswediscoveredthisdevicecan'tbepoweredby
a9Vbatterybecauseofalackofenergy(intermsofsuppliedAmpere).So,you
havetosupplyyourdistancemeterbyusingacomputeroranACadapter(yes,
it'snothandyatall,butthisisjustanexperiment!)

ON/)

(/id/Getting

startedwithBTE13010AduinoMini

Shoppinglist:
ArduinoUNO
USBcable
TheArduinoIDEinstalledonyourPC
SetofDupontcables
MB102breadboard

clone/)

(/id/Simple

calculatorbasedonArduinoMEGA/)

AnHCSR04ultrasonicsensor
LCD16x2display
10kOhmlinearpotentiometer
2N3904transistor(ora2N2222)
Number210kOhmresistor(1/4Watt)
Pushbutton
Piezoelectricbuzzer
Howdoesitworks?
Thesystemtransmitsaburstofultrasonicsoundwavestowardsthesubjectand
thenreceivesthecorrespondingecho.Accordingtothereflectiontime,Arduino
calculatesthedistancethankstothefollowingformula:
Testdistance=(highleveltimespeedofsound*)/2
*speedofsoundinairis340m/s
Ad

Adclosedby
Seenthisad Mq135mq135gassensorair
Alreadybought
Adcovered
multipletimes
this
content
Stopseeingthisadquality...
AdsbyGoogle

Notinterested
inthisad

IDR58,000DapetinapaajadiTokopedia!Yangjual
banyak,banyaaak!SudahcekTokopedia...
Tokopedia

Step1:ConnectingHCSR04ultrasonicmoduletoArduino

(/file/FUSPWPII9WTXSMA/)

HCSR04wiring
TheHCSR04moduledoesn'tneedanyextralibrary.Youjusthavetoconnectit
toArduinofollowingtheattachedFritzingdrawingortheschemebelow:
5V>Vcc
GND>GND
pin7>Trig
pin8>Echo

InternetJakartaPusat

InternetJakartaBarat

Rp240,000/bulan

Rp240,000/bulan

Daftar

Daftar

Uploadingthecode
Now,downloadthefileultrasonic.inoandthendoubleclickonit.ArduinoIDEwill
askyoutosavethenewsketchintoafolderwhosenamewillbethesameone
usedforthe.inofile.Savethefilewhereyouprefer.
Setupfunction
Atthebeginningofthesketch,wedefinethetwopinsusedfortriggerandecho:
inttriggerPort=7;
intechoPort=8;

InordertomaketheHCSR04transmitaburstof8ultrasoundwaves(40kHz),
Arduinosendsapulse(10us)tothepin7.
Intothesetupfunction,weproperlysetthemasOUTPUTandINPUT:
pinMode(triggerPort,OUTPUT);
pinMode(echoPort,INPUT);

Loopfunction
The first four instructions into the loop allow the HCSR04 to transmit
microwavestowardsanobject:
digitalWrite(triggerPort,LOW);

//settoLOWtrigger'soutput

digitalWrite(triggerPort,HIGH);

//senda10uspulsetothetrigg

er
delayMicroseconds(10);
digitalWrite(triggerPort,LOW);

Bysendinga10uspulsetothetriggerPort,Arduinosetsthepin7toHIGH.After
thisinstruction,thesketchwaits10usbeforesettingthepin7LOWagain.
Inthefirstlineofthefollowinginstructions,Arduinoreceivesthereflectiontime
of ultrasonic waves from the HRSR04. This time is needed to calculate the
distancebyusingtheformuladistance=(highleveltimespeedofsound*)/2
showninthesecondline.
longduration=pulseIn(echoPort,HIGH);

longr=3.4*duration/2;

//herewecalculatethedistance

floatdistance=r/100.00;

Thelastlinesdetermineiftheobjectistoofar,checkingifthereflectiontimeis
greaterthan38ms.
if(duration>38000)Serial.println("outofreach");
else{Serial.print(duration);Serial.println("cm");}

Youcanseetheoutputofthissketchinthescreenshotattachedabove.

ultrasonic.ino(/files/orig/FPA/HLNJ/IA0WJZAX/FPAHLNJIA0WJZAX.ino)

ADVERTISEMENT

InternetSalatiga

InternetSurakarta

Rp240,000/bulan

Rp240,000/bulan

Daftar

Daftar

Step2:Addingapushbutton

(/file/FPPPNKEIA0WK0G1/)

Ofcourse,wewantourdistancemetertodomeasurementsonlywhenweneed.
We can simply implement this feature adding a pushbutton. So, pressing a
bushbutton,ArduinoandHCSR04doameasurement.
See the attached Fritzing scheme to see how to connect the pushbutton.
Rememberthata10kOhmresistorisrequiredforthiswiring.
Thefirststepistodeclarethepinusedtoconnectthebutton(wechosethepin
10):
#defineBUTTON10

Then,intothesetupfunction,wesetthispinasanINPUT:
pinMode(BUTTON,INPUT);

Thelastinstructionhastobeputintotheloopfunction:
while(digitalRead(BUTTON)==LOW);

Whatdoesthepreviousinstructiondo?
Whenthepushbuttonisn'tpressed,thelogicalconditioninsidethewhilecycle
is TRUE, so the sketch stays endlessly inside it and will not execute the next
lines.

Onthecontrary,whenthepushbuttonispressed,thelogicalconditionbecomes
FALSEandthesketchcomesoutfromthewhileloopandexecutesthefollowing
linesdoingameasurement.
Asusualyoucandownloadthereadytousesketch.
Asyoucanseeifyoutestthisstep,theserialmonitorwillshowmeasurements
onlywhenthepushbuttonispressed.

ultrasonic_and_button.ino(/files/orig/FL6/54CV/IA0WK0J4/FL654CVIA0WK0J4.ino)

Step3:Connectingalcddisplayandapiezoelectricbuzzer

(/file/F4Q4HLYIA2BT6VT/)

Now it's time to connect the LCD display to our Arduino. As seen in the
Introduction, you'll also need some other things to make this circuit: a 2N3904
transistor (or, alternatively, a 2N2222), a 10k Ohm resistor, a 10k Ohm linear
potentiometerforadjustingthecontrast.Thesecomponentsareneededtomake
theLCDdisplayturnonwhenpressingthepushbuttonduringmeasurements.
Furthermore,addingapiezoelectricspeakercanbeawisechoiceifyouwantto
beinformedwhenthedistancemetergoesoutofreach.
NOTE:wearenotgoingtoexplainhowtoconnectanLCDdisplaytoArduinoas
well as how to control its backlight because these procedures have been
alreadyexplainedinthefifthandsixthstepsofourprevioustutorialrespectively.
howtoconnectanLCDdisplaytoArduino...
(http://www.instructables.com/id/ThermohygrometerwithclockandLCD
displayonArd/step5/ConnectingtheLCDdisplay/)
...andhowtocontrolitsbacklight
(http://www.instructables.com/id/ThermohygrometerwithclockandLCD
displayonArd/step6/ControllingtheLCDdisplaybacklight/)
But if you are only interested in doing the connections, just see the attached
Fritzingscheme.
NOTE:Sincethepin7isnowusedbythedisplay,wechangedthepinusedby
theHCSR04movingittothepin9.
Thesketch

Let'sadaptthesketchaccordingtothechangeswewanttomake.
Inthefirstpartofthesketch,wehavetodeclaretwoconstantsandavariable.
ThefirstconstantisthePWMpinusedtoturnonandoffthedisplaybacklight
andsecondoneisthefrequencyofthenoteplayedbythepiezospeakerwhen
thedistancemetergoesoutofreach.
The variable is needed to set the backlight brightness up to the maximum
value.
#defineLUMIN11
#defineNOTE_A4440
intl=255;

ThenweincludetheLiquidCrystallibraryandinitializetheLCDdisplaylibrary:
//includethelibrarycode:
#include<LiquidCrystal.h>
//initializethelibrarywiththenumbersoftheinterfacepins
LiquidCrystallcd(2,3,4,5,6,7);

Setupfunction
Intothesetupfunctionweneedtodeclarethepin11asanOUTPUTand
initializetheLCDdisplay(16columnsandwith2rows):
pinMode(LUMIN,OUTPUT);
//setuptheLCD'snumberofcolumnsandrows:
lcd.begin(16,2);

Intheloopfunctionwemakesomechanges.Firstofallwemodifythewhileloop
asshownbelow:
while(digitalRead(BUTTON)==LOW){
analogWrite(LUMIN,0);//turnLEDoff
lcd.clear();
noTone(12);
}

When the button is not pressed down, the logical condition is TRUE, as a
consequencethesketchwaitsintothiswhileloop.Inthissituation,thefirstline
in the block turns the backlight off, the second line clears the display and the
thirdoneturnsthetonegeneratoroff.
When the pushbutton is pressed, the logical condition becomes FALSE and
Arduinoskipsthiswhileloopandgoesonexecutingthefollowingline...
analogWrite(LUMIN,l);//turnLEDon

...whichturnsthebacklighton.
Aswearenotusingtheserialmonitoranymore,wehavetochangethe
functionsSerial.printtolcd.print.
lcd.setCursor(0,0);
lcd.print("time:");
lcd.print(duration);
lcd.print("us");
lcd.setCursor(0,1);
if(duration>38000){lcd.println("outofreach");tone(12,NOTE_A4);}

else{lcd.print("dist:");lcd.print(distance);lcd.println("cm");noTone(1
2);}

In the first row the display it prints the reflection time and the distance in the
secondone.Ifreflectiontimeisgreaterthan38ms,theobstacleisoutofreach
and the piezo buzzer will play a sound and the display will show the message

"outofreach",otherwisethesketchwillprintthemeasureddistance.
Asusual,thesketchisreadytobedownloaded.

ultrasonic_button_lcd_buzz.ino
(/files/orig/FOZ/861K/IA2K3U69/FOZ861KIA2K3U69.ino)

Step4:Measurementtests

(/file/F1T1PA0IA1ZHHG9/)

In order to make the device easier to use, we placed the components on a


24x8cm wooden board. We also used two different breadboards: a mini
breadboard for the ultrasonic module and the pushbutton, and a medium size
breadboardfortheothercomponents.
In addition, we installed two essential things to do more accurate
measurements:asimplelaserpointerandatubularspiritlevel.
Thelastusefulthingisacoupleofpaperpipes(oursare7.5cmlong)which
havetobeplacedinfrontofthetwospeakersoftheultrasonicmodule.Theyare
requiredinordertofocustheultrasonicpulsescomingoutfromtheultrasonic
modulespeakers,whichotherwisewoulddivergeexcessively.Infact,according
tothedatasheet,themeasuringangleis15degrees.
Whiledoingmeasurements,wediscoveredthatthepipesarerequiredfor"long
distances"(greaterthan1meter)andmisleadingforshortones.
Thelongestdistancewedidhasbeen418cm.

I MoreComments

FEATURED CHANNELS

Woodworking

Paper
Newsletter

KitchenHacks

paper/)
enteremail

sort=FAVORITES)
I'min!

Puzzles

Space

(/tag/type
(/tag/type
(/tag/type
(/tag/type
Join2million+toreceiveinstant
id/category
id/category
id/keyword
id/category
workshop/channelDIYinspirationinyourinbox.
craft/channel kitchen%20hacks/?play/channel
woodworking/)

puzzles/)

(/tag/type
id/keyword
astronomy/?

IceCream

Homesteading

sort=FAVORITES)sort=FAVORITES)homesteading/)

Mobile
Downloadourapps!
Android(https://play.google.com/store/apps/details?id=com.adsk.instructables)
iOS(https://itunes.apple.com/app/instructables/id586765571)
Windows(http://apps.microsoft.com/windows/enus/app/7afc8194c771441a959054250d6a8300)

AboutUs

FindUs

WhoWeAre(/about/)

Facebook(http://www.facebook.com/instructables)

Advertise(/advertise/)

Youtube(http://www.youtube.com/user/instructablestv)

Contact(/about/contact.jsp)

Twitter(http://www.twitter.com/instructables)

Jobs(/community/PositionsavailableatInstructables/)
Help(/id/howtowriteagreatinstructable/)

Pinterest(http://www.pinterest.com/instructables)
Google+(https://plus.google.com/+instructables)

Resources
ForTeachers(/teachers/)
ArtistsinResidence(/air)
GiftPremiumAccount(/account/give?sourcea=footer)
Forums(/community/)
Answers(/tag/typequestion/?sort=RECENT)
Sitemap(/sitemap/)

TermsofService(http://usa.autodesk.com/adsk/servlet/item?siteID=123112&id=21959721) |
PrivacyStatement(http://usa.autodesk.com/adsk/servlet/item?siteID=123112&id=21292079) |
LegalNotices&Trademarks(http://usa.autodesk.com/legalnoticestrademarks/) | MobileSite(http://www.instructables.com)
(http://usa.autodesk.com/adsk/servlet/pc/index?id=20781545&siteID=123112)
2016Autodesk,Inc.

3DPrinting

Sewing

(/tag/type
(/tag/type
(/tag/type
(/tag/type
id/keyword
id/category
id/category
id/category
ice%20cream/? home/channel technology/channel
craft/channel
3DPrinting/)

sewing/)

You might also like