10 years, 8 months ago.

HC-SR04 ultrasonic sensor

Hi there,

I am really struggling with the HC SR04 ..

Would anyone kindly post a very simple code to control a LED with it please?

That would be a big help.

Thank you ☺

2 Answers

10 years, 8 months ago.

Hello Mr Olieman,

Thank you very much for your prompt reply.

This code has helped me. However, I'm using a mbed application board 769-4182 and tried to display the values in it. . I'm using the code below but the only value I'm getting is 0.

Do I need anything else apart from its library to use the display from the app board ?

  1. include "mbed.h"
  2. include "hcsr04.h"
  3. include "C12832_lcd.h"

DigitalOut myled(LED1); HCSR04 usensor(p25,p6); C12832_LCD lcd;

unsigned int dist;

int main(){

while(1) {

usensor.start(); wait_ms(500); dist=usensor.get_dist_cm(); lcd.cls(); lcd.locate(3,3); lcd.printf("cm: %ld",dist );

}while }main

Thank you very much.

Accepted Answer

Please put <<code>> and <</code>> around your code.

Are you sure you connected your sensor correctly? Vcc to 5V, GND shorted to mbed ground (quite often forgotten when people use another power supply for the sensor!), and the data lines connected correctly? p25 the trigger pin and p6 the echo pin?

posted by Erik - 14 Aug 2013

It works! Pin 6 was not working properly so now I am using pin12 and it works ! Thank you so much indeed!

posted by lincoln almeida 14 Aug 2013

I am having the same problem. The value it gives is always 0. I have checked the connections and changed the pins as well but it hasn't really helped. One quick question I 'm powering HCSR04 through Vout pin of mbed which provides 3.3V regulated output? Is that the problem?

posted by Faizan Ahmad 15 Nov 2013
10 years, 8 months ago.

Have a look at: https://mbed.org/users/prabhuvd/code/HCSR04/