## Arduino and HC-SR04 ultrasonic sensor

10 september 2011 | Classified in: Electronic | Tags: Arduino, Ultrasonic, Sensor, HC-SR04, US-100

Here is just a simple code example.

### Code:

``````
/*
HC-SR04 Ping distance sensor]
VCC to arduino 5v GND to arduino GND
Echo to Arduino pin 13 Trig to Arduino pin 12
*/

#define trigPin 12
#define echoPin 13

void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}

void loop() {
int duration, distance;
digitalWrite(trigPin, HIGH);
delayMicroseconds(1000);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance >= 200 || distance <= 0){
Serial.println("Out of range");
}
else {
Serial.print(distance);
Serial.println(" cm");
}
delay(500);
}
``````

### The Theory Behind It:

In the program above, we want to calculate the distance of an object in front of the ultrasonic sensor. This sensor can send a "ping" at a given moment and receive the ping bouncing back on an object at another given moment.
A ping is nothing but a sound that is inaudible for the human hear and this is why this sensor is called "ultrasonic".
The sensor send a ping at a time t1 and receive the bouncing ping at a time t2.
Knowing the speed of sound, the time difference Δt = t2 - t1 can give us an idea of the distance of an object.

Example, if Δt = 500 microseconds, we know it took 250 microseconds for the ping to hit an object and another 250 microseconds to come back.
The approximate speed of sound in dry air is given by the formula:
c = 331.5 + 0.6 * [air temperature in degrees Celsius]
At 20°C, c = 331.5 + 0.6 * 20 = 343.5 m/s
If we convert the speed in centimetres per microseconds we get:
c = 343.5 * 100 / 1000000 = 0.03435 cm/ųs
The distance is therefore, D = (Δt/2) * c
or D = 250 * 0.03435 = 8.6 cm

Instead of using the Speed of Sound, we can also use the "Pace of Sound".
The Pace of Sound = 1 / Speed of Sound = 1 / 0.03435 = 29.1 ųs/cm
In this case the equation to calculate the distance become: D = (Δt/2) / Pace of sound
and for the example above: D = 250 / 29.1 = 8.6 cm

Randy said: #1 [friday 24 february 2012 at 05:44]

Thanks. This worked perfect on the first try.

rou said: #2 [sunday 04 march 2012 at 17:01]

thank you very much !!!

grisisiknis said: #3 [tuesday 27 march 2012 at 17:48]

bookmarked!!!

elen said: #4 [tuesday 27 march 2012 at 20:05]

how do I send the signal from the US sensor to a buzzer?

int ultraSoundSignal = 7;
int val = 0;
int ultrasoundValue = 0;
int timecount = 0; // Echo counter
int ledPin = 13;
int BUZZ = 4
byte i;

void setup()
{
Serial.begin(9600); // Sets the baud rate to 9600
pinMode(ledPin, OUTPUT); // Sets the digital pin as output
}

void loop()
{
timecount = 0;
val = 0;
pinMode(ultraSoundSignal, OUTPUT); // Switch signalpin to output

/* Send low-high-low pulse to activate the trigger pulse of the sensor
* -------------------------------------------------------------------
*/

digitalWrite(ultraSoundSignal, LOW); // Send low pulse
delayMicroseconds(2); // Wait for 2 microseconds
digitalWrite(ultraSoundSignal, HIGH); // Send high pulse
delayMicroseconds(5); // Wait for 5 microseconds
digitalWrite(ultraSoundSignal, LOW); // Holdoff

/* Listening for echo pulse
* -------------------------------------------------------------------
*/

pinMode(ultraSoundSignal, INPUT); // Switch signalpin to input
val = digitalRead(ultraSoundSignal); // Append signal value to val
while(val == LOW) { // Loop until pin reads a high value
}
while(val == HIGH)
{ // Loop until pin reads a high value
timecount = timecount +1; // Count echo pulse time
}

ultrasoundValue = timecount; // Append echo pulse time to ultrasoundValue
serialWrite('A'); // Example identifier for the sensor
printInteger(ultrasoundValue);
serialWrite(10);
//serialWrite(13);

if(timecount > 0)

{
pinMode(BUZZ,OUTPUT);
for (i=0;i<6;i++)
{
digitalWrite(BUZZ,HIGH);
delay(500);
digitalWrite(BUZZ,LOW);
delay(500);
}
}

Virtualmix said: #5 [saturday 31 march 2012 at 03:58]

@elen: Hello! I would like to help but I don't think I understand what you would like to do.
What is a "US sensor" and how do you want it to interact with a buzzer?
The HC-SR04 is used to calculate a distance but I cannot see any distance calculation in your code.

Mattmouthe said: #6 [thursday 05 april 2012 at 13:18]

See you
Mattmouthe

faithfull said: #7 [friday 06 april 2012 at 00:20]

First of all, nice job!!! And thx for the code.

I have one question, can you help me by coding a lcd panel for the hc-sr04 ? i will get the distance on it.

greetings from germany

Virtualmix said: #8 [friday 06 april 2012 at 17:54]

@faithfull: I can try to help. What modele of LCD panel is it? Have you started writing any code?

faithfull said: #9 [friday 06 april 2012 at 22:11]

i am a absolutly beginner. I am learning by my self with the arduino examples and the www.

But i have no idea how to connect a lcd pannel on a breadboard with the arduino.
I buyed this one here (PDF of my LCD Panal):

Virtualmix said: #10 [saturday 07 april 2012 at 06:17]

@faithfull: You should use the LiquidCrystal Library available for Arduino.
Try to run this example code and then you can modify it to display anything you want, like the distance measured with the HC-SR04 sensor.
From what I can see, your LCD looks like a standard one. It's a bit of a pain to wire it up to the Arduino but if you follow the Arduino tutorial you should be ok.
If you don't want to bother with a lots of cables, you can get a "lcd keypad shield", very cheap from ebay and extremely easy to use. Cheers!

Virtualmix said: #11 [saturday 07 april 2012 at 06:54]

@faithfull: The code will look like that (not tested):

#include <LiquidCrystal.h>

#define trigPin 2
#define echoPin 3

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

void setup() {
lcd.begin(16, 2);
lcd.print("Distance (cm):");
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}

void loop() {
lcd.setCursor(0, 1);
int duration, distance;
digitalWrite(trigPin, HIGH);
delayMicroseconds(1000);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance >= 200 || distance <= 0){
lcd.print("Out of range");
}
else {
lcd.print(distance);
}
delay(500);
}

faithfull said: #12 [saturday 07 april 2012 at 10:40]

thany you very much.

i will try this.
before i started with arduino (one month ago), i thought that the coding must be very difficult and long, but i see, it was much easier...

sham said: #13 [sunday 08 april 2012 at 13:48]

thak you very mucth work fine

faithfull said: #14 [tuesday 10 april 2012 at 14:19]

Hello, it´s me again.
I have one little issue with my HC-SR04. I have just a range between 1 cm and 6 cm.
I can do anything but it wont help, can you help me please ? I took a Video maybee it helps to understand what i am talking about. If nothing is in front of the HC-SR04 it shows 6 cm, and the closest measurement is 1 cm.

faithfull said: #15 [tuesday 10 april 2012 at 15:09]

My friend, i found the issue. my false was that i put the hc-sr04 in the middle of my breadboard. at the end of it, it will give me correct measurements.

thanks :)

Virtualmix said: #16 [wednesday 11 april 2012 at 11:07]

@faithfull: Thanks for the message! I have done the same mistake before but the range was a bit different (only working between 8 & 20cm)...

faithfull said: #17 [friday 20 april 2012 at 00:45]

I want to say thank you again. My HC-SR04 works greate. i have worked a few days on my new code and think it is still perfekt for my. here you can see a short vid of my battleground :)

virtualmix said: #18 [friday 20 april 2012 at 17:53]

@faithfull: your video is awesome and you've done a very nice work with wiring everything together. Thank you so much for sharing the link here!

nick27 said: #19 [friday 20 april 2012 at 18:49]

hi virtual mix...i very impressed at this blog very helpfull.i was strugling alot to undrstand the math behind the sensor but now its cleared..thanks alot.

nick27 said: #20 [friday 20 april 2012 at 18:50]

but i need major help on how to code for the sensor in c using a pic18f452..
i need some serius help with my project..

faithfull said: #21 [friday 20 april 2012 at 19:44]

i will mount this in a toy car as a parkingassistent system :)

Virtualmix said: #22 [monday 23 april 2012 at 12:27]

@ faithfull: Well done mate!

@nick27: I wish I could help but I have absolutely no experience with PIC programming :-/

muffin123 said: #23 [sunday 03 june 2012 at 20:04]

hello,

i am using the hc-sro4 with the ardumoto motor driver shield and the Arexx "Mr. Basic" robot platform. i can't figure out how to make the motors respond to the distances calcuated by the hc-sro4. could someone please help me write the code for it?

Virtualmix said: #24 [monday 04 june 2012 at 10:55]

@muffin123: Could you please give a bit more details? What do you want the motors to do exactly?
Cheers.

muffin123 said: #25 [monday 04 june 2012 at 19:06]

hi,

when the hc-sro4 detectes an object 5 cm from the sensor i want the motors to reverse for 1 second then i want motor A to to go forward and motor B to go backward for 500 miliseconds then i want both motors to go forward.

multifungi said: #26 [tuesday 05 june 2012 at 19:10]

Thanks for the code! I was looking around downloading multiple libraries and your clean code was the only one that worked, now i try to mix it with a waveshield. Thanks!

muffin123 said: #27 [friday 08 june 2012 at 21:13]

hey, Vurtualmix

what's taking you so long to respond? I've been waiting 4+ days...

Virtualmix said: #28 [saturday 09 june 2012 at 14:05]

@muffin123: What you want to do is easy and I am sure you can do it yourself, especially with all the example code above.

Now, 5 cm is very close distance from the sensor, I recommend you to use a larger range (15cm seems more reasonable) in order to have better results.

Here is a little bit of help but you will need to improve this yourself.
//------------------------------------------------------------------------------------------//
#define trigPin 12
#define echoPin 13
//This is where you will plug the motors, change it if necessary
#define MotorForwardA 5
#define MotorBackwardA 6
#define MotorForwardB 7
#define MotorBackwardB 8
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
//set motors as output
pinMode(MotorForwardA, OUTPUT);
pinMode(MotorBackwardA, OUTPUT);
pinMode(MotorForwardB, OUTPUT);
pinMode(MotorBackwardB, OUTPUT);
}
void loop() {
int duration, distance;
digitalWrite(trigPin, HIGH);
delayMicroseconds(1000);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance >= 200 || distance <= 0){
Serial.println("Out of range");
}
else if (distance <= 15){
digitalWrite(MotorBackwardA, HIGH);
digitalWrite(MotorBackwardB, HIGH);
digitalWrite(MotorForwardA, LOW);
digitalWrite(MotorForwardB, LOW);
delay(1000);
digitalWrite(MotorBackwardA, LOW);
digitalWrite(MotorBackwardB, HIGH);
digitalWrite(MotorForwardA, LOW);
digitalWrite(MotorForwardB, LOW);
delay(500);
digitalWrite(MotorBackwardA, LOW);
digitalWrite(MotorBackwardB, LOW);
digitalWrite(MotorForwardA, HIGH);
digitalWrite(MotorForwardB, HIGH);
}
delay(500);
}

muffin123 said: #29 [sunday 10 june 2012 at 03:55]

thank you so much for the code!!!

Samuel Dette said: #30 [thursday 14 june 2012 at 19:19]

Hi there, nice job and thanks for the code! It works but I still got two problems. First is, that the frequency of messuarind the distance is to low. I need that to be faster for using the "US-sensor" ;) as an instrument for a live-performance. The other thing that worries me is the irregularity that comes up sometimes. Once in every 5-10 "Messuares" there is a totally wrong number that (in my project) would make a strange noise (and that woulnd't be nice...)

Can you help me with that?

Cheers, Samuel

Samuel Dette said: #31 [thursday 14 june 2012 at 19:29]

Actually the wrong messuared values pop up every 5th time and if you come to a distance further than 40 cm the values get even more unreliable.

And my 3rd problem is the very wide spread of the "ultrasonic wave beam". I actually wanted to put the senosr on the floor and work within distancies between 20 - 200 cm. But the ultrasonic wont get reflected by my hand if I am further away than aprox 80 cm...

I would be very glad, if someone could help me here.

Greets to faithfull as well from germany :)

Rizz said: #32 [wednesday 20 june 2012 at 10:52]

hi
i tried to build a program based on your code to make 2 hc-sr04 working but it seems like both of my sensor are not working.here is my program.please help me

#define trigPin1 13
#define echoPin1 12
#define trigPin2 11
#define echoPin2 10
#define led1 7
#define led2 6
#define led3 5

void setup()
{
Serial.begin (9600);
pinMode (trigPin1, OUTPUT);
pinMode (echoPin1, INPUT);
pinMode (trigPin2, OUTPUT);
pinMode (echoPin2, INPUT);
pinMode (led1, OUTPUT);
pinMode (led2, OUTPUT);
pinMode (led3, OUTPUT);
}

void loop()
{
int duration1, distance1, duration2, distance2;
digitalWrite (trigPin1, HIGH);
digitalWrite (trigPin2, HIGH);
delayMicroseconds(1000);
digitalWrite (trigPin1, LOW);
digitalWrite (trigPin2, LOW);
duration1 = pulseIn(echoPin1, HIGH);
distance1 = (duration1/2) / 29.1;
duration2 = pulseIn(echoPin2, HIGH);
distance2 = (duration2/2) / 29.1;

if (distance1 >= 200 || distance1 <= 0)
{
Serial.println ("out of range");
}
else if (distance1 > 0 && distance1 <= 10 && distance2 > 0 && distance2 <= 10)
{
digitalWrite (led1, HIGH);
digitalWrite (led2, HIGH);
digitalWrite (led3, HIGH);
Serial.print(distance1);
Serial.println(" cm");
}
else if (distance1 >= 10 && distance1 <= 20 && distance2 >= 10 && distance2 <= 20)
{
digitalWrite (led1, LOW);
digitalWrite (led2, HIGH);
digitalWrite (led3, HIGH);
Serial.print(distance1);
Serial.println(" cm");
}
else if (distance1 >= 20 && distance1 <= 30 && distance2 >= 20 && distance2 <= 30)
{
digitalWrite (led1, LOW);
digitalWrite (led2, LOW);
digitalWrite (led3, HIGH);
Serial.print(distance1);
Serial.println(" cm");
}
else if (distance1 >= 10 && distance1 <= 20 && distance2 >= 20 && distance2 <= 30)
{
digitalWrite (led1, LOW);
digitalWrite (led2, HIGH);
digitalWrite (led3, HIGH);
Serial.print(distance1);
Serial.println(" cm");
}
else if (distance1 > 0 && distance1 <= 10 && distance2 >= 20 && distance2 <= 30)
{
digitalWrite (led1, HIGH);
digitalWrite (led2, LOW);
digitalWrite (led3, HIGH);
Serial.print(distance1);
Serial.println(" cm");
}
else
{
digitalWrite (led1, LOW);
digitalWrite (led2, LOW);
digitalWrite (led3, LOW);
Serial.print(distance1);
Serial.println(" cm");
}
delay(500);
}

mithun said: #33 [thursday 28 june 2012 at 17:51]

If any one know,how to write micro-c cord to use ping sensor(3-pin sonar sensor)
by using "mikroC PRO for PIC" help me.
thanks.

Virtualmix said: #34 [friday 29 june 2012 at 17:32]

@Samuel Dette: For your first issue, I would recommend to add a loop in the code and average the measured values. You will loose a bit of accuracy per reading but will get consistent results.
The second issue is simply a limitation of the sensor, you need to use it at a certain level above the ground to receive a decent measurement.

@Rizz: Do one sensor at the time, (code for first sensor, then code for second sensor) instead of combining them together.

@mithun: Sorry I have no experience with PIC, maybe someone else here can help.

Anthony said: #35 [monday 09 july 2012 at 18:02]

change
int duration, distance;
to
float duration, distance;
for maybe more precision

Anthony said: #36 [monday 09 july 2012 at 18:26]

And if you have a thermistor, you can plug that in to get current temp of where your sensor is

float duration, distance;
digitalWrite(trigPin, HIGH);
delayMicroseconds(1000);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance >= 200 || distance <= 0){
Serial.println("Out of range");
}
else {
Serial.print(distance);
Serial.println(" cm");
}
delay(500);

Anthony said: #37 [monday 09 july 2012 at 18:27]

Code example using termistor

girish gujar said: #38 [thursday 02 august 2012 at 19:41]

does any 1 have avr code for this??

BB haji said: #39 [thursday 02 august 2012 at 22:38]

Hi,
would someone tell me how you get the command line to show you the reading for the distance?
I have uploaded the code and then what?
thank you

Titch said: #40 [friday 14 september 2012 at 14:23]

I uploaded this worked first time no issues. on test found to be precise has given a basis for experimentation thanks. nice explanation on the math straight forward and to the point and good worked example are you a tutor by chance lol?

Titch said: #41 [friday 14 september 2012 at 15:00]

@mithun: on a PIC you will have a T0INT pin which is timer 0 interupt pin or depending on the PIC it might be T1INT or words to that effect you set the timer to count clearing the timer overflow flag in the INTCON reg measure the duration of the count from the interupt of the pulse.... also use a zener diode in reverse bias to clamp input and reduce noise. But the code is vastly more complicated on PIC than in arduino I would personnally recommend using arduino for what you are trying to do but if you are going to use PIC regardless perhaps a 16F690 would be a good 1 to use as you can program the Fosc from about 36KHz to 8MHz and prescaler 1/256. I wish you good luck in your project

llama said: #42 [sunday 30 september 2012 at 20:23]

thank you~ and nice background song haha

Tim Shaw said: #43 [tuesday 09 october 2012 at 18:34]

Hello.

Thanks for this, its great. I got it working reading centimetres straight away.

Do you know if there any way to internally route the PMW signal to MIDI that can be ready MAX or Ableton?

I want the different signal values to correspond to different notes playable by the synths in Ableton. I am quite new to code do you know where I would put the corresponding code in the sketch?

Any help would be very much appreciated.

Thanks
T

NN said: #44 [thursday 18 october 2012 at 08:02]

can anyone help my problem out. i want to change the distance from centimeter into percentage. can anyone help me how to create the program?

virtualmix said: #45 [friday 19 october 2012 at 13:48]

@NN: In the program above, replace this part:

else {
Serial.print(distance);
Serial.println(" cm");
}

With this:

else {
distance = distance/80*100;
Serial.print(distance);
Serial.println(" percent");
}

This is assuming 80cm is the maximum distance (100%) and 0 cm is the minimum distance (0%).

Disclamer: Not tested but it should work. Adapt if necessary.

Ehrenmal said: #46 [tuesday 23 october 2012 at 04:25]

Hello, thank you very much for the code. It seems to be the only reliable one.

The only issue I have is that it stops detecting at about 37 cms or so. The sensor is supposedly detects up to 400cm or so I read.

Is this true? Is there a way to augment its reach?

virtualmix said: #47 [tuesday 23 october 2012 at 13:02]

@Ehrenmal: Glad to hear the code is useful.
The operating range for the sensor shown on the video is from 10cm to 80cm. This is not something you can modify yourself. If you need a different operating range you will have to use a different sensor. Have a look at infrared sensors (Sharp Sensors are cheap and easy to use).
If your sensor stops detecting at 37cm, ensure there is enough clearance below the sensor. Someone had a same issue in comments above.

Jihru said: #48 [saturday 03 november 2012 at 08:29]

Hi.!. Please help me on my project. I need asm code for ultrasonic sensor. I am using US-100 UltraSonic Sensor and PIC16F877A. What the code needs to do is detect object within 1-8 centimeters from sensor then it has to blink an LED to indicate that there is an object within that range. I really appreciate it if anyone can help me.

HaiYang said: #49 [thursday 08 november 2012 at 15:36]

Since the datasheet mentions that the trigger input signal should last for 10us, wouldn't it be better to delay the trigPin for 10 microseconds?

virtualmix said: #50 [friday 09 november 2012 at 09:19]

@HaiYang: Thank you for your comment, if in the datasheet then it's probably a very good idea! I will test and modify my article when I get a chance and if it gives good result :-)

geonn said: #51 [wednesday 21 november 2012 at 16:31]

Hi! I'm trying to connect 4 Sr04 sensors but when i try to grab distances from more than two sensors, the serial seems to lag. Do you know what i can do for that?

geonn said: #52 [wednesday 21 november 2012 at 16:42]

here is my code::

int trigPin[] = {6,8,10,12};
int echoPin[] = {7,9,11,13};
int duration[4], distance[4];

void setup() {
Serial.begin (115200);
for (int i=0; i<4; i++) {
pinMode(trigPin[i], OUTPUT);
pinMode(echoPin[i], INPUT);
}
}

void loop() {
for (int i=0; i<4; i++) {
digitalWrite(trigPin[i], HIGH);
delayMicroseconds(1000);
digitalWrite(trigPin[i], LOW);
duration[i] = pulseIn(echoPin[i], HIGH);
Serial.print("<");
Serial.print(duration[i]);
Serial.print("-");
Serial.print(i);
Serial.print(">");
delayMicroseconds(500);
}
}

sara said: #53 [sunday 16 december 2012 at 20:13]

Hi
thank u so much
did you use at mega8 microcontroller for programming??

virtualmix said: #54 [thursday 20 december 2012 at 11:33]

@sara: I used an Arduino Uno with an ATmega 328

virtualmix said: #55 [thursday 20 december 2012 at 11:40]

@geonn: I am not sure exactly why your code is not working but if I were you I would do four different function, one per sensor. Then call these functions independently in loop{} and test each one of them separately for debugging.
(It's just an idea I haven't tested...)

thomas said: #56 [wednesday 26 december 2012 at 12:29]

how do you connect it to an out put and could you give me a diagram (i dont know these things got it the arduino at christmas and im only 11

Richard said: #57 [friday 28 december 2012 at 12:25]

Many thanks. Your example worked first time! Now I know my sensor works, time to build my first bot! :-D

Steven said: #58 [wednesday 09 january 2013 at 18:22]

Is it possible to use 2 sensors, one on either side, and then add them together so that the printout on the LCD screen only shows one number, the totals from both sensors added together....please help me, I need this for a project. Thanks a lot.

aries said: #59 [thursday 10 january 2013 at 16:12]

how can I make a program using the ultrasonic sensor ping))) in connection with my arduino board? our project is a sensor that will provide the obstruction/object for the blind people? do you know a program?

ammon D said: #60 [friday 25 january 2013 at 20:55]

I cannot get it to print to the serial monitor, this error comes up when I try to upload: avrdude: stk500_getsync(): not in sync: resp=0x00. My OS is Windows 7, does that have anything to do with it?

Vikash said: #61 [friday 22 february 2013 at 13:32]

Scott said: #62 [friday 19 july 2013 at 17:20]

int error = 0;
byte type = 0;
byte vibrate = 0;

//Arduino PWz Speed Control for DFRobot Motor Shield (default pins)
int M1 = 12;
int M2 = 13;
int E1 = 3;
int E2 = 11;
int trigPin = 10; // this is suppose to be for the ultrasonic sensor
int echoPin = 2; // this is suppose to be for the ultrasonic sensor
int lmotor = 0;
int rmotor = 0;

void setup()
{
Serial.begin(57600);

// set pin modes for Arduino Motor Shield
pinMode(M1, OUTPUT);
pinMode(M2, OUTPUT);
pinMode(trigPin, OUTPUT); // this is suppose to be for the ultrasonic sensor
pinMode(echoPin, INPUT); // this is suppose to be for the ultrasonic sensor

error = ps2x.config_gamepad(7,5,4,6, true, true); //setup pins and settings: GamePad(clock, command, attention, data, Pressures?, Rumble?) check for error

if(error == 0)
{
Serial.println("Found Controller, configured successful");
Serial.println("Try out all the buttons, X will vibrate the controller, faster as you press harder;");
Serial.println("holding L1 or R1 will print out the analog stick values.");
Serial.println("Go to www.billporter.info for updates and to report bugs.");
}
else if(error == 1)
{
Serial.println("No controller found, check wiring, see readme.txt to enable debug. visit www.billporter.info for troubleshooting tips");
}
else if(error == 2)
{
Serial.println("Controller found but not accepting commands. see readme.txt to enable debug. Visit www.billporter.info for troubleshooting tips");
}
else if(error == 3)
{
Serial.println("Controller refusing to enter Pressures mode, may not support it. ");
}

if (type != 1)
{
}
}

void loop()
{
if(error == 1) //skip loop if no controller found
return;
if (type == 1)
{

lmotor = 0;
if (ps2x.Button(PSB_L1))
lmotor = 255;
if (ps2x.Button(PSB_L2))
lmotor = -255;

rmotor = 0;
if (ps2x.Button(PSB_R1))
rmotor = 255;
if (ps2x.Button(PSB_R2))
rmotor = -255;

}
else
{
lmotor = 0;
rmotor = 0;
}

// update motors
if (lmotor < 0)
{
digitalWrite(M1, LOW);
analogWrite(E1, -lmotor); //PWM Speed Control
}
else
{
digitalWrite(M1, HIGH);
analogWrite(E1, lmotor); //PWM Speed Control
}

if (rmotor < 0)
{
digitalWrite(M2, LOW);
analogWrite(E2, -rmotor); //PWM Speed Control
}
else
{
digitalWrite(M2, HIGH);
analogWrite(E2, rmotor); //PWM Speed Control
}

delay(30);
}

Virtualmix said: #63 [saturday 20 july 2013 at 09:19]

@ Scott: I understand you would like to use the sensor for collision detection, is that right?

sumanth said: #64 [tuesday 23 july 2013 at 18:49]

can any1 let me know how to make a ultrasonic flaw detector?? please!!

sam said: #65 [wednesday 24 july 2013 at 19:46]

I need some help with putting together programs in a arduino mega. can any one help?

manju said: #67 [saturday 14 september 2013 at 16:22]

Hi,
I have arduino uno atmega 328 pu , HC-SR04 US & L298N duel h bridge motor drive
http://www.hobbyking.com/hobbyking/store/__37421__Arduino_Compatible_H_Bridge_Motor_Driver.html.
I saw codes separately everywhere but unable to found one code that can do my job.I want to build 2WD obstacle avoiding robot can you help me ? :)

Blackie said: #68 [thursday 19 september 2013 at 07:28]

hi Sir.. can help me how to write microC pro programming ultrasonic +pic16f877+buzzer.. thank u sir

shuhab said: #69 [sunday 22 september 2013 at 17:04]

programme runs perfectly works accurately but have some problem in not getting answers in decimals

Santosh said: #70 [monday 23 september 2013 at 18:01]

Hello sir i want to make the electronic travel aid for blind that means measuring distance from the obstacle that can be helpful for blind people and i want the code to interface that signal to the headset of an blind people through microcontroller.

electronoobie said: #71 [tuesday 24 september 2013 at 07:23]

weird i keep getting outputs like this

5cm
out of range
5cm
out of range

any idea why this happens?

sasidhar said: #72 [tuesday 24 september 2013 at 12:06]

can u tell me how to introduce sounds in energia..??

rutuja dodake said: #73 [thursday 26 september 2013 at 16:26]

sir i want the pgm for interfacing of ultrasonic transducer HC-SR04 andbeagleboard n how to interface with it???

Dryvendra said: #74 [thursday 26 september 2013 at 17:30]

Hai sir. I'm using Arduino Mega 2560 R3. As my final year project work, i want do low cost assistance kit for wheelchair users. So , there is some web sites give the idea on low cost assistance kit. My problem is, i have the micro controller code...

#include <LiquidCrystal.h>

//BEGINS LCD

//lcd(rs,rw,enable,data4,data5,data6,data7)

LiquidCrystal lcd(30,31,32,33,34,35,36);

// backlight is pin 15

int backLight = 40; //set the pin

//ENDS LCD

//BEGINS DISTANCE SENSOR

const unsigned int sensorPin = 22;

long distance, tempDistance;

//ENDS DISTANCE SENSOR

//BEGINS BUZZER

const unsigned int buzzerPin = 12; //which is PB6

//ENDS BUZZER

//BEGINS PHOTORESISTOR

int count;

int ledPin = 44;

const unsigned int PHOTO_1 = 0;

const unsigned int PHOTO_2 = 1;

boolean on_off;

//ENDS PHOTORESISTOR

ISR(TIMER3_COMPA_vect)

{

if(!on_off) //off

{ //if it is dark for 3 seconds, then turn on the headlight

if((analogRead(PHOTO_1) <= 55) && (analogRead(PHOTO_2) <= 55)) //check the status of the

//photoresistor

{

count++;

}

else

{

count = 0;

}

if(count == 3)

{

on_off = true;

count = 5; //hold the headlight to be on for 5 seconds

}

}

else //on

{

if(count > 0) //count down the headlight to be on

{

count--;

}

else

{ //check the status of the photoresistor. If it is not dark, turn it off; otherwise keep the

{

count++;

}

else

{

on_off = false;

}

}

}

}

void setup()

{

//buzzer setup

TCCR1A |= _BV(COM1B1); //set OC1B which is PB6 and it will toggle

TCCR1B |= _BV(CS11) | _BV(CS10); //set prescaler to be 64

//frequency is 250khz

TCCR1A |= _BV(WGM10); //Set up Waveform Generation Mode 9… OCR1A as TOP, update OCR1A

TCCR1B |= _BV(WGM13);

pinMode(buzzerPin, OUTPUT); //set the PB6 to be output

//lcd setup

pinMode(backLight, OUTPUT); //set the backlight pin to be output

digitalWrite(backLight, HIGH); //turn on the backlight

lcd.begin(2,16); //set the dimension of LCD

lcd.clear(); //set a blank screen

lcd.setCursor(5,0);

lcd.print('Hello');

delay(1500);

lcd.clear();

lcd.setCursor(0,0); //column, row

lcd.print('Distance Light');

lcd.setCursor(5,1);

lcd.print('Cm');

//photoresistor setup

on_off = false;

count = 0;

pinMode(ledPin, OUTPUT); //set the headlight pin to be output

TCCR3A = 0; //Normal timer operation.

TCCR3B = _BV(WGM32) | _BV(CS32) | _BV(CS30); //CTC & prescaler 1024

OCR3AH = (15624 & 0xFF00) >> 8; //Setting the Output Compare Register to 15624 gives us an

//interrupt at every second

OCR3AL = (15624 & 0x00FF); // frequency is 15625 hz per second

TIMSK3 = _BV(OCIE3A); //set up the interrupt when OCR3A is equal TCNT3

}

void loop()

{

int i = 0;

lcd.setCursor(0,0); //set the cursor of the text to be displayed

distance = 600; //set the distance to be infinite at the beginning

for(i;i<8;i++)

{

tempDistance = distanceInCentimeters(sensorPin+i); //get the distance of the sensor

if(tempDistance < distance) //store the lowest distance

{

distance = tempDistance;

}

delay(5); //delay for 5ms before checking the next sensor

}

lcd.setCursor(1,1); //display the distance on LCD

if(distance > 99)

{

lcd.print(distance);

}

else

{

lcd.print(' ');

lcd.print(distance);

}

buzzer(distance); //call buzzer function

}

long microsecondsToCentimeters(long microseconds)

{

// The speed of sound is 340 m/s or 29 microseconds per centimeter.

// The ping travels out and back, so to find the distance of the

// object we take half of the distance travelled.

return microseconds / 29 / 2;

}

//DISTANCE SENSOR FUNCTION

long distanceInCentimeters(int sensorPin)

{

//generate a sonar pulse

pinMode(sensorPin, OUTPUT); //set the pin to be output

digitalWrite(sensorPin, LOW); //set the pin to be “0″ for 2 microseconds

delayMicroseconds(2);

digitalWrite(sensorPin, HIGH); //set the pin to be “1″ for 5 microseconds

delayMicroseconds(5);

digitalWrite(sensorPin, LOW); //set the pin to be “0″

pinMode(sensorPin, INPUT); //set the pin to be input

return microsecondsToCentimeters(pulseIn(sensorPin, HIGH)); //return the distane in cm

}

//BUZZER FUNCTION

void buzzer(long distance)

{

if(distance <= 30)

{

TCCR1B |= _BV(CS11) | _BV(CS10); //set prescaler to be 64

pinMode(buzzerPin, OUTPUT);

OCR1A = 1000;

OCR1B = OCR1A/2; //250 hz (250000/1000)

}

else if(distance >= 30 && distance <= 40)

{

TCCR1B |= _BV(CS11) | _BV(CS10); //set prescaler to be 64

pinMode(buzzerPin, OUTPUT);

OCR1A = 1500;

OCR1B = OCR1A/2; //166hz (250,000/1500)

}

else if(distance >=40 && distance <=50)

{

TCCR1B |= _BV(CS11) | _BV(CS10); //set prescaler to be 64

pinMode(buzzerPin, OUTPUT);

OCR1A = 2500;

OCR1B = OCR1A/2; //100hz

}

else

{

pinMode(buzzerPin, INPUT); //set the PB6 to be input

TCCR1B &= ~_BV(CS10) & ~_BV(CS10);

}

}

//To turn on or off the headlight

{

lcd.setCursor(12,1);

if(on_off) //if it is dark outside

{

lcd.print('ON ');

digitalWrite(ledPin, HIGH);

}

else //it is not dark outside

{

lcd.print('OFF');

digitalWrite(ledPin, LOW);

}

}

but here i want change the sensor Ping))) to Hc -Sr04 sensor and i wan use 4 sensor. Sadly, i don't know how to program it. So i need help from you guys.... urgent

PASSION said: #75 [thursday 10 october 2013 at 22:40]

I WANT A PROG. that usesa buzzer and us-100 sonar

PASSION said: #76 [thursday 10 october 2013 at 22:42]

when the sonar detect you the buzzer wll alarm

Andre said: #77 [wednesday 13 november 2013 at 16:52]

im making a program with arduino hc sr04. Does anyone know whats the code for setting an alarm when a number goes out of technical specification?

Sanato said: #78 [friday 22 november 2013 at 13:37]

I am going to make a blind stick with 3 ultrasonic sensor to detect obstacle in left right and straight through arduino but unknown about coding in arduino......
Please can anybody help me for coding....

ramon said: #79 [saturday 30 november 2013 at 21:22]

Hi

great program and nice detail of how the sensor works . thanks for helping out beginners like me. thanks

stojan said: #80 [sunday 12 january 2014 at 23:14]

when i verify it it's ok but when i try to upload to do arduino it says:
"avrdude: stk500_getsync(): not in sync: resp=0x30"
P.S. sorry on bad english :)

bigbopper said: #81 [wednesday 05 february 2014 at 01:41]

I need help , does any body have code ,to read ultrasonic , for a plasma thc . touch off .
, pierce height , and cut height arduino mega

asdas said: #82 [friday 07 february 2014 at 00:19]

how to reverse the measuring of the sensor ?

soumyadip mukherjee said: #83 [tuesday 25 february 2014 at 05:35]

how do i connect a motor driver and a ultrasonic sencer with arduino uno and how do I program when obeject is very close (about 5 cm) with ulttasonic sencer motor will autometic stop and when object go from there motor will autometic start again .please comment

dinesh said: #84 [saturday 15 march 2014 at 03:06]

sir,
i am doing project using arduino, hcsr04, and accelerometer adxl335, and l293d. the theme is to control the motors using accelerometer and if obstacle comes the motors stop and dont move forward but access to other directions. please any one help for me by giving code

Cesar said: #85 [tuesday 25 march 2014 at 20:45]

I have a project that I am working on and was wondering if I could use your assistance. It is a matter of incorporating the HC-SR04 to an existing program and I see you have a great deal of experience. please feel free to e mail me any time. I appreciate it.

Cesar said: #86 [thursday 27 march 2014 at 14:30]

Hello Virtualmix ,

can you help me please. this is the code I have it is for a impact tester, I want to incorporate a LCD screen to it so I can get reading off the HC-SR04. can you please help me because I am lost. I am definitely a beginner but I have learned hands on.

cesar said: #87 [thursday 27 march 2014 at 14:33]

Sorry I forgot to post this in my last post, but this is what I have and it might not be right, but like I said I am a beginner, and I have learned everything hands on. so I bought the HC-SR04 with the SainSmart LCD4884 and I am trying to get it all in here to function.

//const int doorSwitch = 3;
const int proximitySwitch = 4; //tup connected with retrevial assembly
const int towerSeated = 5; //not used
const int eStopSwitch = 6;
const int echoPin = 7; //Echo Pin
const int trigPin = 8; //Trigger Pin
const int LEDPin = 13; //Onboard LED
const int pressureLow = 32; //when this pin is LOW, pressure is too low
const int pressureHigh = 31; //when this pin is LOW, pressure is too high
const int redLight = 35; //pin will turn on red light
const int greenLight =36; //pin will turn on green light
const int winchDirection =39;//
const int winchPower = 40; //always set low before switching pin 39 high or low
const int heightGate = 41; //
const int speedGate = 42; //Phototransistor mounted at bottom, velocity and brakes
const int jhookDrop = 43; //activates solenoid, releases drop assembly
const int jhookGrab = 44; //activates solenoid, moves jhooks to lifting position
const int brakeRelease = 45; //activates solenoid, cylinder compresses springs releasing brakes

//variables to store state of sensors
int proximityState;
int eStopState;
int brakeState;
int doorState;
int heightState;
int speedState;
int pressureHighState;
int pressureLowState;
int currentHeightState;

int heightCounter =0;
int maximumRange = 200; // Maximum range needed
int minimumRange = 0; // Minimum range needed
long duration, distance; // Duration used to calculate distance

String inputString =""; //a string to hold incoming data
boolean stringComplete =false; //whether the string is complete
char cmd;

//tells current action
boolean pickupInProgress =false;
boolean movingUp =false;
boolean movingDown =false;
boolean notHighEnough =false;

//prevents partial reads from height sensor
//long lastDebounceTime = 0; //the last time the output pin was toggled
//long debounceDelay = 10; //the debounce time; increase if the output flickers

void setup(){
//initialize serial:
Serial.begin(9600);
//reserve 200 bytes for the inputString:
inputString.reserve(200);
pinMode(3,INPUT);
pinMode(4,INPUT);
pinMode(6,INPUT);
pinMode(7,INPUT);
pinMode(8,OUTPUT);
pinMode(13,OUTPUT);
pinMode(31,INPUT);
pinMode(32,INPUT);
pinMode(35,OUTPUT);
pinMode(36,OUTPUT);
pinMode(39,OUTPUT);
pinMode(40,OUTPUT);
pinMode(41,INPUT);
pinMode(42,INPUT);

pinMode(43,OUTPUT);
pinMode(44,OUTPUT);
pinMode(45,OUTPUT);

digitalWrite(greenLight,HIGH);

}

void loop(){
//print the srting when a newline arrives:
if(stringComplete){
switch(cmd){
case 'c':
//connect
Serial.println("c");
//clear the string:
inputString = "";
stringComplete =false;
break;
case 'r':
//raise winch
pickupInProgress =false;

movingUp =true;
movingDown =false;
digitalWrite(winchPower,LOW); //turn the winch power off
delay(500); //wait
digitalWrite(winchDirection,LOW); //set winch direction
//
delay(500); //wait for a second
digitalWrite(winchPower,HIGH); //turn the winch power ON
Serial.println("r");
//clear the string:
inputString ="";

stringComplete =false;
break;
case's':
//stop winch
digitalWrite(winchPower,LOW);
Serial.println("s");
inputString ="";

stringComplete =false;
pickupInProgress =false;
break;
case'l':
//lower winch
pickupInProgress =false;
movingUp =false;
movingDown =false;
digitalWrite(winchPower,LOW); //turn the winch power off
delay(500); //wait

digitalWrite(winchDirection,HIGH); //set winch direction

delay(500); //wait for half a second
digitalWrite(winchPower,HIGH); //turn the winch power ON
Serial.println("l");
//clear the string:
inputString = "";
stringComplete = false;
break;

case'p':
digitalWrite(jhookDrop,LOW);//close jhooks
digitalWrite(jhookGrab,HIGH);
Serial.println("p");
inputString = "";
stringComplete = false;
break;

case'd':
//open J-hooks,drop tup
digitalWrite(jhookGrab,LOW);
digitalWrite(jhookDrop,HIGH);
Serial.println("d");
inputString = "";
stringComplete = false;
break;

case'o':
//opens breaks
digitalWrite(brakeRelease,HIGH);
Serial.println("o");
inputString = "";
stringComplete = false;
break;

case'b':
//lock breaks
digitalWrite(brakeRelease,LOW);
Serial.println("b");
inputString = "";
stringComplete = false;
break;

case'g':
//open J-hooks
digitalWrite(jhookGrab,LOW);
digitalWrite(jhookDrop,HIGH);

//lower winch until it hits drop assembly
Serial.println("g");
//clear the string:
inputString = "";
stringComplete =false;

//lower winch
digitalWrite(winchPower,LOW); //turn the winch power off
delay(500); //wait
digitalWrite(winchDirection,HIGH); //set winch direction
delay(500); //wait for half a second

digitalWrite(winchPower,HIGH); //turn the winch power ON

pickupInProgress =true;
movingDown =true;

break;

case'a':
//raises tup to 256
heightCounter = 0;
Serial.println("a");
//clear the string:
inputString = "";
stringComplete = false;

notHighEnough = true;
pickupInProgress = false;
movingUp = true;
movingDown =false;

//opens breaks
digitalWrite(brakeRelease,HIGH);

digitalWrite(winchPower,LOW); //turn the winch power off
delay(500); //wait
digitalWrite(winchDirection,LOW); //set winch direction
//
delay(500); //wait for a second
digitalWrite(winchPower,HIGH); //turn the winch power ON
break;

case'T':
//check state of proximity switch to see if drop assembly and retreival apperatus are connected
//High = connected
if(proximityState==HIGH){
Serial.println("T0");
}
else{
Serial.println("T1");
}
inputString = "";
stringComplete = false;
break;

// case'D':
//check state door
if(doorState==HIGH){
Serial.println("D0");
}
else{
Serial.println("D1");
}
inputString = "";
stringComplete = false;
break;

case'P':
//check state of pressure
if(pressureHighState==LOW){
Serial.println("P1");
}
else{
if(pressureLowState==LOW){
Serial.println("P2");
}
else{
Serial.println("P0");
}
inputString = "";
stringComplete = false;
break;
}
}

/*******************************************************************/
//test area,delete when finished
/*

//emergency stop actions
if(heightState==LOW){
digitalWrite(greeLight,HIGH);
}
else{
//turn LED off:
digitalWrite(greenLight,LOW);
}
*/
/*******************************************************************/
//read the state of the emergency stop button:

//emergency stop actions
if(eStopState==LOW){
//turn off motor
digitalWrite(winchPower,LOW);
//lock brakes
digitalWrite(brakeRelease,LOW);
//turn on red light
digitalWrite(redLight,HIGH);
}
else{
//turn LED off:
digitalWrite(redLight,LOW);

}

/*******************************************************************/
//action for g command
//keeps the winch moving down until tup limit switch
if(pickupInProgress==true)
{
//if tup is connected, stop motor and grab tup
if(proximityState==HIGH
)
{
digitalWrite(winchPower,LOW);
delay(300);

digitalWrite(jhookDrop,LOW);//close jhooks
digitalWrite(jhookGrab,HIGH);

pickupInProgress = false;
}
//safety stops
if(eStopState==LOW){
pickupInProgress = false;
}
if(doorState==LOW){
//turn off motor
digitalWrite(winchPower,LOW);

pickupInProgress = false;
}

}
/*******************************************************************/
/* The following trigPin/echoPin cycle is used to determine the
distance of the nearest object by bouncing soundwaves off of it. */
digitalWrite(trigPin, LOW);
delayMicroseconds(2);

digitalWrite(trigPin, HIGH);
delayMicroseconds(10);

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

//Calculate the distance (in cm) based on the speed of sound.
distance = duration/58.2;

if (distance >= maximumRange || distance <= minimumRange){
/* Send a negative number to computer and Turn LED ON
to indicate "out of range" */
Serial.println("-1");
digitalWrite(LEDPin, HIGH);
}
else {
/* Send the distance to the computer using Serial protocol, and
turn LED OFF to indicate successful reading. */
Serial.println(distance);
digitalWrite(LEDPin, LOW);
}

delay(50);
}

if(heightState!=currentHeightState){
//lastDebounceTime = millis();

//if ((millis() - lastDebounceTime)>debounceDelay){

if(heightState==HIGH)
{
//if the state has changed, increment the counter
if(movingUp==true){
//if the current state is HIGH then the button
//went from off to on:
heightCounter++;
}
else{
//if the current state is LOW then the button
//went from on to off:
heightCounter--;
}
/*
if(heightCounter %8== 0){
digitalWrite(greenLight,HIGH);
Serial.println(heightCounter);
Serial.println(notHighEnough

);
}
else{
digitalWrite(greenLight,LOW);
}
*/
//}
}
}
//save the current state as the last state,
//for next time through the loop
currentHeightState = heightState;

/*******************************************************************/
//action for the a command
//keeps the winch moving down until tup limit switch
if(notHighEnough==true)
{
//if height is above 256,stop
if(heightCounter>=256)
{
digitalWrite(winchPower,LOW);
notHighEnough = false;
}
//safety stops
if(eStopState==LOW){
notHighEnough = false;
}
if(doorState==LOW){
//turn off motor
digitalWrite(winchPower,LOW);
notHighEnough = false;
}
}

}
/*******************************************************************/

/*
SerialEvent occurs whenever a new data comes in the
hardware serial RX. This routine is ran between each
time loop() runs, so using delay inside loop can delay
response. multiple bytes of data may be available.
*/;
;
void serialEvent(){
while(Serial.available()){
//get the new byte:

inputString += inChar;
//if the incoming character is a newline, set a flag
//so the main loop can do something about it:
if(inChar=='c'){
cmd = inChar;
stringComplete = true;
}
if(inChar=='p'){
cmd = inChar;
stringComplete = true;
}
if(inChar=='d'){
cmd = inChar;
stringComplete = true;
}
if(inChar=='r'){
cmd = inChar;
stringComplete = true;
}
if(inChar=='l'){
cmd = inChar;
stringComplete = true;
}
if(inChar=='s'){
cmd = inChar;
stringComplete = true;
}
if(inChar=='b'){
cmd = inChar;
stringComplete = true;
}
if(inChar=='o'){
cmd = inChar;
stringComplete = true;
}
if(inChar=='B'){
cmd = inChar;
stringComplete = true;
}
if(inChar=='D'){
cmd = inChar;
stringComplete = true;
}
if(inChar=='P'){
cmd = inChar;
stringComplete = true;
}
if(inChar=='T'){
cmd = inChar;
stringComplete = true;
}
if(inChar=='g'){
cmd = inChar;
stringComplete = true;
}
if(inChar=='a'){
cmd = inChar;
stringComplete = true;
}

}
}

Cesar said: #88 [friday 28 march 2014 at 17:00]

CAN ANYONE HELP!!!

shailesh said: #89 [monday 31 march 2014 at 20:08]

Sir plz can i get d code for obstacle detection using hcsr04 arduino uno and micro servos for vibrational feedback...its urgent,..plz help

Prases said: #90 [thursday 01 may 2014 at 13:06]

How to connect four ultrasonic sensor to arduino Megha for obstacle avoidance

sarushi said: #91 [wednesday 11 february 2015 at 15:14]

Hi, I am working on a project to interface ultrasonic senor HC SR04 to Ti launchpad TM4C123gh6pmi. Can anybody suggest me a code for the same?

vamsi said: #92 [saturday 28 february 2015 at 08:22]

I saw your project with HC SR04 and I thought you the right person to help me on MSP430g2553. I am a noob and its my first step in electronics.Please help me out.here goes my project.

I am working with HC SR04(ultrasonic sensor).,MSP430G2553 and TLC5940nt. I want to display a message using TLC5940nt when the HC SR04 detects an object.

P2.1 to VCC

P2.2to GND

P2.4 to trigger

P2.1 to echo

For TLC5940nt,

P1.0 to XLAT

P1.1 to BLANK

P1.3 to DCPRG

P1.4 to GSCLK

P1.5 to SCLK

P1.7 to SOUT

P1.6 to SIN

P2.6 to XERR

P2.7 to VPRG

Regards,

Vamsi Krishna.R

Sammy said: #93 [saturday 07 march 2015 at 04:21]

I get distance measurements just fine at first, but once I exceed the maximum range, I can't get the device to start measuring again. It just stops. Anybody have any ideas?

## Write a comment

What is the first letter of the word kyhn? :