Ultrasonic Distance sensor using HC-SR04

Tips, Tricks and methods for programming, learn ways of making your programming life easier, and share your knowledge with others.

Moderators: Benj, Mods

User avatar
Valued Contributor
Valued Contributor
Posts: 8536
Joined: Sat May 05, 2007 2:27 pm
Location: Northamptonshire, UK
Has thanked: 2456 times
Been thanked: 3525 times

Re: Ultrasonic Distance sensor using HC-SR04

Postby medelec35 » Thu Sep 21, 2017 8:37 am

kalmar79 wrote:ok I did again in another file and working good

That's good, do you know what you did different to make it work?

kalmar79 wrote:I want to introduce a buzzer insted a led. do I need to modificate something?

You have two ways to go.
1) is with a 5V sounder with built-in driving circuitry.
2) A piezo type sounder which requires a driving waveform e.g. PWM.
Due to age of your microcontroller, it does not have any useful functions built-in .
E.e. PWM, analogue to digital converters, internal oscillator etc.
So with that in mind the second option is possible but is complex.
This is because of the need to be bit banged while sill allowing detection function.
So with your chip, option one would be easiest as you just put 5V DC in and it will buzz.
If the buzzer takes more than the current that a pin can supply then you will required an additional transistor for controlling power to the buzzer.

kalmar79 wrote:Why you use '320' in (Echo = 0) || (count > 320) ??

How the Proximity detector works is a pulse of 10us is sent into the trigger pulse input which causes a burst of ultrasonic sound to be generated.
Then the microcontroller waits for a signal caused by receiving sound wave that was generated by the trigger.
So its waiting in a tight loop.
What if the sound is not received back?
Then it will stay stuck in a tight loop.

Code: Select all

count > 320
just acts as a timeout function.
If the signal is not received within a few milliseconds then exit tight loop and resend trigger pulse.


If you read a post that is useful, please show appreciation by clicking on thumbs up Icon.

Posts: 45
Joined: Sun Aug 20, 2017 8:18 pm
Been thanked: 4 times

Re: Ultrasonic Distance sensor using HC-SR04

Postby kalmar79 » Fri Sep 22, 2017 6:08 am

my friend thanks for take the time to explain me. I only change the file or carpet were I was doing the flowchart, I do it in english and spanish but the only one word I change was count(contador in spanish). I don't know what happened.
And I put a buzzer in the output and work good.
Is possible make a PWM with the switch funtion? I made something like this for a servomotor.