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.
Diff: HCSR04.cpp
- Revision:
- 4:d76458b00616
- Parent:
- 3:9ddabd24f48c
diff -r 9ddabd24f48c -r d76458b00616 HCSR04.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/HCSR04.cpp Sun Dec 03 18:47:45 2017 +0000 @@ -0,0 +1,60 @@ +#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; +} \ No newline at end of file