Sie sind auf Seite 1von 13

1/4/2015

ArduinoBasics:HCSR04UltrasonicSensor
16

Lainnya BlogBerikut

BuatBlog Masuk

Arduino Basics
AnArduinoblogthatfollowsthefootstepsofanenthusiasticArduinouser,fromthegroundup.Level:Basic
Home

ArduinoBasicsProjectsPage

FeedbackPage

11November2012

SearchThisBlog

HCSR04UltrasonicSensor

Search

Translate
PilihBahasa
Diberdayakanoleh

Terjemahan

Introduction:
The HCSR04 Ultrasonic Sensor is a very affordable proximity/distance sensor that has been used mainly
forobjectavoidanceinvariousroboticsprojects.ItessentiallygivesyourArduinoeyes/spacialawareness
andcanpreventyourrobotfromcrashingorfallingoffatable.Ithasalsobeenusedinturretapplications,
waterlevelsensing,andevenasaparkingsensor.ThissimpleprojectwillusetheHCSR04sensorwithan
ArduinoandaProcessingsketchtoprovideaneatlittleinteractivedisplayonyourcomputerscreen.

Pages
ArduinoBasicsProjectsPage
ArduinoBasicsYouTube
Videos
FeedbackPage
Home

PartsRequired:
FreetronicsElevenoranycompatibleArduino.
HCSR04UltrasonicSensor
MiniBreadboard4.5cmx3.5cm
Protoshieldandfemaleheaderpins(notessentialbutmakesitmoretidy)
Wirestoconnectitalltogether

Subscribe
Posts
Comments

MyArduinoVideos

TheVideo:

poweredby

TheArduinoSketch:

BlogArchive
2014(9)
2013(13)
2012(11)
December(2)

http://arduinobasics.blogspot.com/2012/11/arduinobasicshcsr04ultrasonicsensor.html

1/13

1/4/2015

ArduinoBasics:HCSR04UltrasonicSensor
November(1)
HCSR04
Ultrasonic
Sensor
October(1)
August(2)
July(2)
June(1)
May(2)
2011(25)

TotalPageviews

1,116,613
TheabovesketchwascreatedusingFritzing.

ArduinoCode:
YoucandownloadtheArduinoIDEfromthissite.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

/*
HCSR04Pingdistancesensor:
VCCtoarduino5v
GNDtoarduinoGND
EchotoArduinopin7
TrigtoArduinopin8

ThissketchoriginatesfromVirtualmix:http://goo.gl/kJ8Gl
HasbeenmodifiedbyWinkleinkhere:http://winkleink.blogspot.com.au/2012/05/arduinohcsr04ultrasonicdistance.html
AndmodifiedfurtherbyScottChere:http://arduinobasics.blogspot.com.au/2012/11/arduinobasicshcsr04ultrasonicsensor.html
on10Nov2012.
*/
#defineechoPin7//EchoPin
#definetrigPin8//TriggerPin
#defineLEDPin13//OnboardLED
intmaximumRange=200;//Maximumrangeneeded
intminimumRange=0;//Minimumrangeneeded
longduration,distance;//Durationusedtocalculatedistance
voidsetup(){
Serial.begin(9600);
pinMode(trigPin,OUTPUT);
pinMode(echoPin,INPUT);
pinMode(LEDPin,OUTPUT);//UseLEDindicator(ifrequired)
}
voidloop(){
/*ThefollowingtrigPin/echoPincycleisusedtodeterminethe
distanceofthenearestobjectbybouncingsoundwavesoffofit.*/
digitalWrite(trigPin,LOW);
delayMicroseconds(2);
digitalWrite(trigPin,HIGH);
delayMicroseconds(10);

digitalWrite(trigPin,LOW);
duration=pulseIn(echoPin,HIGH);

//Calculatethedistance(incm)basedonthespeedofsound.
distance=duration/58.2;

if(distance>=maximumRange||distance<=minimumRange){
/*SendanegativenumbertocomputerandTurnLEDON
toindicate"outofrange"*/
Serial.println("1");
digitalWrite(LEDPin,HIGH);
}

http://arduinobasics.blogspot.com/2012/11/arduinobasicshcsr04ultrasonicsensor.html

2/13

1/4/2015

ArduinoBasics:HCSR04UltrasonicSensor
51
52
53
54
55
56
57
58
59
60

else{
/*SendthedistancetothecomputerusingSerialprotocol,and
turnLEDOFFtoindicatesuccessfulreading.*/
Serial.println(distance);
digitalWrite(LEDPin,LOW);
}

//Delay50msbeforenextreading.
delay(50);
}

Thecodeabovewasformattedusinghilite.me

ProcessingCode:
YoucandownloadtheProcessingIDEfromthissite.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61

/*ThefollowingProcessingSketchwascreatedbyScottCon
the10Nov2012:http://arduinobasics.blogspot.com/

InspiredbythisProcessingsketchbyDanielShiffman:
http://processing.org/learning/basics/sinewave.html

*/
importprocessing.serial.*;
intnumOfShapes=60;//Numberofsquarestodisplayonscreen
intshapeSpeed=2;//Speedatwhichtheshapesmovetonewposition
//2=Fastest,Largernumbersareslower
//GlobalVariables
Square[]mySquares=newSquare[numOfShapes];
intshapeSize,distance;
StringcomPortString;
SerialmyPort;
/*Setup*/
voidsetup(){
size(displayWidth,displayHeight);//Useentirescreensize.
smooth();//drawsallshapeswithsmoothedges.

/*CalculatethesizeofthesquaresandinitialisetheSquaresarray*/
shapeSize=(width/numOfShapes);
for(inti=0;i<numOfShapes;i++){
mySquares[i]=newSquare(int(shapeSize*i),height40);
}

/*OpentheserialportforcommunicationwiththeArduino
MakesuretheCOMportiscorrectIamusingCOMport8*/
myPort=newSerial(this,"COM8",9600);
myPort.bufferUntil('\n');//TriggeraSerialEventonnewline
}
/*Draw*/
voiddraw(){
background(0);//MakethebackgroundBLACK
delay(50);//Delayusedtorefreshscreen
drawSquares();//Drawthepatternofsquares
}
/*serialEvent*/
voidserialEvent(SerialcPort){
comPortString=cPort.readStringUntil('\n');
if(comPortString!=null){
comPortString=trim(comPortString);

/*UsethedistancereceivedbytheArduinotomodifytheyposition
ofthefirstsquare(otherswillfollow).Shouldmatchthe
codesettingsontheArduino.Inthiscase200isthemaximum
distanceexpected.Thedistanceisthenmappedtoavalue
between1andtheheightofyourscreen*/
distance=int(map(Integer.parseInt(comPortString),1,200,1,height));
if(distance<0){
/*Ifcomputerreceivesanegativenumber(1),thenthe
sensorisreportingan"outofrange"error.Convertall
ofthesetoadistanceof0.*/

http://arduinobasics.blogspot.com/2012/11/arduinobasicshcsr04ultrasonicsensor.html

3/13

1/4/2015

ArduinoBasics:HCSR04UltrasonicSensor
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128

distance=0;
}
}
}
/*drawSquares*/
voiddrawSquares(){
intoldY,newY,targetY,redVal,blueVal;

/*SettheYpositionofthe1stsquarebasedon
sensorvaluereceived*/
mySquares[0].setY((heightshapeSize)distance);

/*Updatethepositionandcolourofeachofthesquares*/
for(inti=numOfShapes1;i>0;i){
/*Usetheprevioussquare'spositionasatarget*/
targetY=mySquares[i1].getY();
oldY=mySquares[i].getY();

if(abs(oldYtargetY)<2){
newY=targetY;//Thishelpstolinethemup
}else{
//calculatethenewpositionofthesquare
newY=oldY((oldYtargetY)/shapeSpeed);
}
//Setthenewpositionofthesquare
mySquares[i].setY(newY);

/*Calculatethecolourofthesquarebasedonits
positiononthescreen*/
blueVal=int(map(newY,0,height,0,255));
redVal=255blueVal;
fill(redVal,0,blueVal);

/*Drawthesquareonthescreen*/
rect(mySquares[i].getX(),mySquares[i].getY(),shapeSize,shapeSize);
}
}
/*sketchFullScreen*/
//ThisputsprocessingintoFullScreenMode
booleansketchFullScreen(){
returntrue;
}
/*CLASS:Square*/
classSquare{
intxPosition,yPosition;

Square(intxPos,intyPos){
xPosition=xPos;
yPosition=yPos;
}

intgetX(){
returnxPosition;
}

intgetY(){
returnyPosition;
}

voidsetY(intyPos){
yPosition=yPos;
}
}

Thecodeabovewasformattedusinghilite.me

Ifyoulikethispage,pleasedomeafavourandshowyourappreciation:

16

http://arduinobasics.blogspot.com/2012/11/arduinobasicshcsr04ultrasonicsensor.html

4/13

1/4/2015

ArduinoBasics:HCSR04UltrasonicSensor

Havealookatmypatreonpage.
VisitmyArduinoBasicsGoogle+page.
FollowmeonTwitterbylookingforScottC@ArduinoBasics.
HavealookatmyvideosonmyYouTubechannel.

However,ifyoudonothaveagoogleprofile...
Feelfreetosharethispagewithyourfriendsinanywayyouseefit.
PostedbyScottCat22:47

+16 Recommend this on Google

Labels:Arduino,ArduinoBasics,code,HCSR04,Processing,rangesensor,Serial,Ultrasonic

57comments:
JeffBowen 29November2012at13:11
Cool.Igotitworkingandit'sprettyneat.GonnatossaroundsomeideasinmyheadofwhatIcando
withit.
Thanks.
Reply
Replies
ScottC 29November2012at22:46
Iwouldbeinterestedtoknowwhatyoucomeupwith:)
Reply

justinfriedman 11March2013at07:13
Myprocessingscreenisallblack,igetdistancereadingsinthearduinoIDE.whyisthis?
Reply
Replies
ScottC

11March2013at15:53

Make sure that you close the Serial Monitor on the Arduino IDE before running the
processingsketch.
Reply

Bes 20May2013at23:07
Coolproject!
Wherehaveyoudownloadedthefritzingpartfortheultrasonicsensor?

http://arduinobasics.blogspot.com/2012/11/arduinobasicshcsr04ultrasonicsensor.html

5/13

1/4/2015

ArduinoBasics:HCSR04UltrasonicSensor
Reply
Replies
ScottC

21May2013at07:10

IamprettysurefromtheFritzingwebsite.FrommemoryIthinktheyhadaforumwhere
peoplecouldcontributeFritzingparts.HavenotbeentothatsiteforawhilebutIampretty
sure that's where I got it from. However Fritzing has been through some major changes
sincethen.

ScottC

21May2013at08:28

Hereisthedownloadlinkasofthe21stMay2013:
DOWNLOADHERE
OralternativelyvisitthepageyourselfandsearchforHCSR04:
FritzingcustompartsWebpage
Reply

Danzl 5June2013at00:50
Beginnerhere,Ihavea64bitsystemthereforeIdownloadedthe64bitversionofProcessing,but
when I try to run this example appears "serial is only compatible with the 32bit download of
Processing"
Anyhelp?Thanks
Reply
Replies
ScottC

5June2013at07:02

HiDanzl,
I think I fell for the same trap. I had to resort to downloading the 32bit version instead,
becausethe64bitversiondoesnotsupportSerial.
Scott

Danzl 17June2013at14:59
Thankyouverymuchfortakingthetimetohelpme,...andImsorryfortakingsolongin
answer back. At the moment I was hurry trying to finishing a little project, and I have
anotherChromebookwithUbuntu12.04installed,Icheckthereifwasworkinganditdoes
soIjustfinishitandforgetitforaboutaweek.NowinvacationImcheckingsomeother
projecttolearnsomethingelsefromyourpage.Thanksagainforallyouramazingwork.
Reply

AkshayKhatri 8June2013at03:26
echopinwillbehighonceitreceivesbackthesignal.thereforepulsein(echopin,HIGH)willgivethe
duration for which the echopin receives the signal..it will not give the total time for the signal.. but
onlythetimeforwhichtheechosensorreceivesit..
Reply
Replies
ScottC

8June2013at08:16

Iamnotsurewhatyoumean.Canyoupleaseexplainfurther.ThanksScott

Anonymous 2September2013at20:47
Iamalsoconfusedaboutthesamething.pulseInreadsthelengthoftimewhereechoPin
receivesthesignal,butshouldn'titreadthetimebetweensendingthepulseandreceiving
it with echoPin? In other words woudn't it make more sense to set duration =
pulseIn(echoPin,LOW)?

http://arduinobasics.blogspot.com/2012/11/arduinobasicshcsr04ultrasonicsensor.html

6/13

1/4/2015

ArduinoBasics:HCSR04UltrasonicSensor
Steve 4January2014at01:31
HeyScott,
IthinkI'mconfusedaboutthesamethinghere(I'mabeginnersoI'mconfusedalot).
digitalWrite(trigPin,LOW)
delayMicroseconds(2)
digitalWrite(trigPin,HIGH)
delayMicroseconds(10)
digitalWrite(trigPin,LOW)
duration=pulseIn(echoPin,HIGH)
//Calculatethedistance(incm)basedonthespeedofsound.
distance=duration/58.2
FromwhatIsee,yousendapulsethatis10microsecondslongandthenusePulseInto
readthelengthofthatpulseagain?Shouldn'titbeusingLOWinsteadofHIGHtoreadthe
time it takes before receiving the pulse? Maybe I don't understand the PulseIn function
wellenoughorIdon'tunderstandthesensor(haven'treceivedmineyet).
Thanks,Steve

ScottC

4January2014at03:15

HISteve,
AllexamplesthatIhaveseenonthenetseemtohaveitsetthisway.
I am pretty sure the digitalWrites are there to initialise the sensor, and then the pulseIn
measuresthepulse.IhavereadthatbysettingpulseIntoHigh,thatthesensorwillpulse:
LOW_HIGH_LOW...
You can try setting it to LOW and see what happens... but I have not seen it setup that
way.
Ifyoudodecidetodoitthatwaythenpleaseletmeknowhowyougo.
Regards
Scott

Steve 4January2014at04:38
ThanksScott,Iwilltestthiswhenmysensorarrives.
Reply

MandakhOyunerdene 2September2013at17:02
HelloScott.Iwouldliketoasksomething.Iamnewtoarduino.Iwannadoaprojectthatisapower
linedetection.So,canthisHCSR04sensordetectthedistanceoftightsurfacelikeafinger?Have
youtrytodistancemeasureoftightsurface?Thankyou.
Md
Reply
Replies
ScottC

16October2013at21:38

ifitcanbouncesoundwaves,thenitwillwork.
Reply

DanSchiffer 6October2013at03:36
NewtoArduinoIDE.Icouldn'tgetanycommunicationfromArduinoMega2560toProcessingPDE
onmyMac.Icouldn'tfigureoutwhichserialcomporttouse,soIchangedthispieceofcode
/*OpentheserialportforcommunicationwiththeArduino
MakesuretheCOMportiscorrectIamusingCOMport8*/
myPort=newSerial(this,"COM8",9600)
myPort.bufferUntil('\n')//TriggeraSerialEventonnewline
}

http://arduinobasics.blogspot.com/2012/11/arduinobasicshcsr04ultrasonicsensor.html

7/13

1/4/2015

ArduinoBasics:HCSR04UltrasonicSensor
tothis
/*OpentheserialportforcommunicationwiththeArduino
MakesuretheCOMportiscorrectIamusingCOMport8*/
myPort=newSerial(this,Serial.list()[0],9600)
myPort.bufferUntil('\n')//TriggeraSerialEventonnewline
}
Now it works fine. I used Daniel Schiffman's sketch Example 198: Reading From Serial Port as a
basis for making this change. On my Mac /dev/tty.usbmodemfaXXX is the port used for
communicationwithArduinoandProcessing.Howeverobvious,Ididnotrealizeitwas[0].
HowcanIdeterminetheactualportnumber?
Thanksforthesketch!
Reply
Replies
ScottC

16October2013at21:40

IknownothingaboutmacsbutIwouldsayyoucouldhavealookattheportbeingused
bytheArduinoIDE(normallydisplayedatthebottomoftheArduinoIDE)
Reply

Anonymous 21October2013at14:39
ThatsAwesomemen,thankforsharethis!
Reply

snowwiteandthe7monkeys 11November2013at00:15
perrrrrrrrrrrrrrrrrrrrrrrrrfecto!wellasidosaysomyselfthisreallyhelpedexceptijusthadtomakea
weensychangefromthediagramwithtonsofresearch:)
Reply

Anonymous 23November2013at21:03
Iffoundanerror..
Change:comPortString=cPort.readStringUntil('\n')
TocomPortString=(newString(cPort.readBytesUntil('\n')))
Reply
Replies
Anonymous 24November2013at23:51
thankyounowitisworking.
Reply

HASHBROWN:D 12December2013at09:50
Heythankyousomuchforthediagramandcode.Thecodehelpedmealot,sinceI'mabeginner
andIcan'twritecodesyet,althoughIhavestartedtocopyandpastefromdifferentcodesintoone
codeformyownrobot(anditworked:D).SinceIhavethekindofbreadboardthathasnegativesand
positives,Ihadtobringthewiresfromthe5VandGNDintotheand+.Butthesensorisawesome,
thankyousomuch!
Reply
Replies
Anonymous 12December2013at09:52
yea,hashbrown'sright.thnxalotscott!

ScottC

12December2013at19:10

That'sgreathashbrown,andyouarewelcomeanonymous.
Feelfreetopostalinktoyourprojectorshareavideoofyourrobotinaction.

http://arduinobasics.blogspot.com/2012/11/arduinobasicshcsr04ultrasonicsensor.html

8/13

1/4/2015

ArduinoBasics:HCSR04UltrasonicSensor
Reply

WilliamMakinen 6January2014at02:08
WhenItrytoruntheprocessingsketch,anerrorcomesupsayingthefunctionreadStringUntil(char)
does not exist. When that happens, this line of code is highlighted comPortString =
cPort.readStringUntil('\n')
I'mabeginner,andwouldappreciatethehelp
Reply
Replies
ScottC

6January2014at07:18

ThisisaproblemwiththenewversionofProcessing:
Change:comPortString=cPort.readStringUntil('\n')
To:comPortString=(newString(cPort.readBytesUntil('\n')))
Reply

Anonymous 14January2014at02:44
ididwhatyouexplainnedinthepicturteshouldicopythecodeonthearduinoprogrambytheword
ori'mgoingtotakeoffsomethings
Reply
Replies
ScottC

14January2014at08:15

If you plan to run this complete project. You can copy and paste the arduino sketch and
uploadittothearduino.Andthencopyandpastetheprocessingsketchtotheprocessing
IDE, and run it. However you may need to modify the com port based on you specific
setupandoperatingsystem.
Reply

balkanskikanali 30January2014at19:57
OnequestionaboutthecubesScott,whichpartneedstobechangedsowhentheapplicationstarts
cubesareupandwithgoingfarfromsensortheycomedown?
Thanks...youarethebest
Reply
Replies
ScottC

31January2014at17:53

Icannotrememberifthisworksornotbutfeelfreetotry
changethis:
distance=int(map(Integer.parseInt(comPortString),1,200,1,height))
to
distance=int(map(Integer.parseInt(comPortString),1,200,height,1))
Reply

Anonymous 13February2014at10:16
hi can anyone help me? i got a problem running the code its say that
>processing.app.SerialNotFoundException: Serial port 'COM1' not found. Did you select the right
onefromtheTools>SerialPortmenu?
pleasehelpme,thanks!
Reply
Replies
ScottC

13February2014at14:49

http://arduinobasics.blogspot.com/2012/11/arduinobasicshcsr04ultrasonicsensor.html

9/13

1/4/2015

ArduinoBasics:HCSR04UltrasonicSensor
Make sure to connect and upload the Arduino Sketch to the Arduino before running the
Processingsketch.MakenoteofwhichcomportyouareusingforyourArduino.Lookat
thebottomrighthandsideoftheArduinoIDE(afterupload).
Also make sure to close the Arduino IDE Serial Monitor before running the Processing
sketch.

Anonymous 13February2014at16:28
thanks Scott i solve the problem, but i have another problem here > avrdude:
stk500_getsync():notinsync:resp=0x00
canuhelpmeagain?thanksinadvance!

ScottC

14February2014at17:46

WhatArduinoboardareyouusing?HaveyouselectedthisboardintheArduinoIDE?
AndhaveyouconfirmedyouareusingthecorrectCOMport?
Reply

Anonymous 18February2014at01:50
IsthereanycodingsforcrackdetectioninaplainsurfaceusingUlrasonicsensor??..
Reply
Replies
ScottC

18February2014at16:26

notonthisblogbutsomeonesurelyhasdonethissomewhereontheinternet
Reply

israalobedy 15April2014at01:34
Hiii
Please if I have parallax ping ultrasonic sensor how I connected it with arduino and how
programmingittosenddatathroughxbeesheildandmodule?.
Ihopetohelpme....
Reply
Replies
ScottC

16April2014at08:22

Idon'thaveaparallaxpingultrasonicsensorbutthissitemayhelp.
AsforXBeecommunicationIhaveanpartiallycompletedtutorialwhichmayhelpyouto
getstarted,buttherearemanytutorialsoutthereontheinternetthatshowyouhowtodo
this.
Trytodoeachoftheseseparatelybeforetryingtojoinorcombinethem.
Reply

TheBunny 2May2014at08:28
thesecondblockofcodethrowssomanyerrors.thefirstoneisok.howdoiknowifitworked???
Reply
Replies
ScottC

2May2014at13:19

Dunno!
Vaguequestion,vagueresponse.Needtobeabitmorespecific.

TheBunny 3May2014at02:49
ActuallyIhadwhitescreenanditwasatcom8andiusecom3.Iamnoob...um,nowithas
blackscreenwithblueboxesatthebottombutnothingmoves...whenihovermyhand.:/
whatmayidowrong?:/thankss

http://arduinobasics.blogspot.com/2012/11/arduinobasicshcsr04ultrasonicsensor.html

10/13

1/4/2015

ArduinoBasics:HCSR04UltrasonicSensor

TheBunny 3May2014at06:21
Actually,
I think that my sensor is broken. The above is not working...it keeps returning 1 at my
serialmonitor.

ScottC

3May2014at09:23

Okseemslikeyouworkedthroughmostofyourproblems.
Just make sure that you use the 32 bit version of Processing IDE because 64bit version
doesnotsupportSerial.
Your sensor keeps returning 1 because it is calculating a distance that exceeds the
maximumorminimumranges.Trytoextendtheserangesifpossibletoseetherawvalues
comingthrough,orjustprinttherawvalueinstead.
Usingtheserialmonitorisagoodwaytocheckthefunctionalityofthesensor.Onceyou
findvaluescomingthrough,thenusetheProcessingIDE,butyoucannothavetheSerial
monitoropenwhenyouruntheProcessingsketchbecauseitwillcreateerrors.
Reply

TheBunny 10May2014at22:10
Doineedanyextralib?:/Ireadsomewherethatineedtodownloadsomemorelibtowork...
Reply
Replies
ScottC

10May2014at22:43

Notwiththissensor
Reply

PrasadPendke 22May2014at13:36
Thiscommenthasbeenremovedbyablogadministrator.
Reply
Replies
ScottC

26May2014at10:07

HiPrasad,
Youwillneedtoaskthatquestioninaforum.
Sorry.
Scott
Reply

Anonymous 29May2014at13:46
HiScott,greatguide.Ijustwantedtoknowwhereyougotthevalue58.2fromintheline:
//Calculatethedistance(incm)basedonthespeedofsound.
distance=duration/58.2
Doyoumindexplainingthederivationaswellplease?
Reply
Replies
ScottC

11June2014at00:37

duration=pulseIn(echoPin,HIGH)
durationistheamountoftimetakenforthesoundtotravelfromthemoduletotheobject
andbackinmicroseconds.
Soundtravelsat340m/sec.
or34000cm/sec

http://arduinobasics.blogspot.com/2012/11/arduinobasicshcsr04ultrasonicsensor.html

11/13

1/4/2015

ArduinoBasics:HCSR04UltrasonicSensor
or340cm/millisecond
or0.034cm/microsecond
Soyoucanmultiplyduration(inmicroseconds)by0.034andthenhalveittogetdistance,
ordividedurationby29.4andthenhalveittogetdistance.
(duration/29.4)/2=duration/58.8
SohowdidIget58.2?
Iusedsomeoneelse'scalculationforthespeedofsound,andassumedthatthenumber
of29.1wascorrectandmultiplieditby2toget58.2.Sothereyougoyoucanchange
thatnumberto58.8.
Didthathelp??

Anonymous 1July2014at00:53
What if you wanted inches, ft, or meters? Would you just have to change that "58.2" to
somethingelse?Because,asIlookatitrightnow,that"58.2"willgiveyoucm,socanyou
inputanothernumbertogiveyouanotherunitofdistance?

ScottC

1July2014at07:01

Correct
Reply

ScottC

19August2014at10:54

DearAnonymous:
Thanksforyourquestion.IhavedeletedyourquerybecauseIthinkyouwouldhavebettersuccess
inaforum.
ArduinoForum
ProcessingForum
WhileIwouldlovetoworkthroughtheproblemsinyourparticularproject,Ijustdon'thavethetime.
Ihardlyhavethetimetoworkthroughtheproblemsinmyown:)

Reply

EmilMashiah 30December2014at23:39
HiScott,reallygreatjob.Iwouldbegladtoseeotheryouprojects.
Keepthegoodwork.
Reply
Replies
ScottC

31December2014at09:57

ThanksEmil.
Feelfreetolookattheprojectspageithasalistofmyotherprojects
Regards
ScottC
Reply

Enteryourcomment...

Commentas:

GoogleAccount

Publish

Preview

http://arduinobasics.blogspot.com/2012/11/arduinobasicshcsr04ultrasonicsensor.html

12/13

1/4/2015

ArduinoBasics:HCSR04UltrasonicSensor

Feelfreetoleaveacomment:

NewerPost

Home

OlderPost

Subscribeto:PostComments(Atom)

2.5k

ThisWeek'sMostPopularPosts

MostRecentPosts

433MHzRFmodulewithArduinoTutorial1

Oneinamillion

SimpleArduinoSerialCommunication

DIYCanonIntervalometerusingArduino

HCSR04UltrasonicSensor
BluetoothAndroidProcessing1

ArduinoSelfie
RelayModule
GroveWaterSensor

BluetoothTutorial1

RecentPostsWidgetbyHelplogger

AwesomeInc.template.PoweredbyBlogger.

http://arduinobasics.blogspot.com/2012/11/arduinobasicshcsr04ultrasonicsensor.html

13/13

Das könnte Ihnen auch gefallen