Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Dependents: Obstacle_avoidance servourfmatlab hcsr04 DistanceOnSevenSegLed ... more
You are viewing an older revision! See the latest version
Homepage
Overview¶
The HC-SR04 ultrasonic sensor uses sonar to determine distance to an object like bats or dolphins do. It offers excellent range accuracy and stable readings in an easy-to-use package. It operation is not affected by sunlight or black material like Sharp rangefinders are (although acoustically soft materials like cloth can be difficult to detect).
HCSR04¶
You can find the details of the sensor at http://www.micropik.com/PDF/HCSR04.pdf

Code¶
include the mbed library with this snippet
#include "mbed.h"
#include "hcsr04.h"
#include "TextLCD.h"
DigitalOut myled(LED1);
HCSR04 usensor(p25,p6);
TextLCD lcd(p14, p16, p17, p18, p19, p20,TextLCD::LCD16x2); // rs, e, d4-d7
unsigned int dist;
int main()
{
unsigned char count=0;
while(1) {
usensor.start();
wait_ms(500);
dist=usensor.get_dist_cm();
lcd.cls();
lcd.locate(0,0);
lcd.printf("cm:%ld",dist );
count++;
lcd.locate(0,1);
lcd.printf("Distance =%d",count);
}
}