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.
HCSR04.cpp
- Committer:
- reesey
- Date:
- 2017-12-03
- Revision:
- 0:3373f4da46c1
- Child:
- 1:27ee973552a9
File content as of revision 0:3373f4da46c1:
#include "mbed.h"
#include "HCSR04.h"
/*
HCSR04.h
Written by Leong Kum Loong.
04 Dec 2017, REV. 0
All routines and functions in this library are written by me solely.
Library for HC-SR04 Ultrasonic Ranging sensor.
Library uses pins p21 to send pulse to sensor Trigger input & p22 to read sensor Echo output.
This is assuming velocity of sound rate from ultrasonic pulse is 340m/s.
*/
DigitalOut trig(p21);
DigitalIn echo(p22);
Timer echoTime;
Ticker interval;
float distance = 0;
float divisor;
static void findDistance(){
trig = 1;
wait_ms(10);
trig = 0;
wait_ms(20);
trig = 1;
wait_us(10);
trig = 0;
while(!echo);
echoTime.start();
while(echo);
echoTime.stop();
distance = (float)echoTime.read_us()/(float)2 * 0.034 / (float)divisor;
echoTime.reset();
}
//Start monitoring distance.
void getDistance(int unit){
//1 for CM & 2 for INCH
switch(unit){
case 1:
divisor = 1; //Default divisor to get CM.
break;
case 2:
divisor = 2.54; //Divisor to get INCH.
break;
}
interval.attach(findDistance, 0.1);
}
//Retrieve distance stored.
float readDistance(){
return distance;
}