Library for controlling ultrasonic ranging module HCSR04 Ported by hiawoood from arduino library orgininally created by ITead studio.

Committer:
sas638
Date:
Sun May 08 20:09:39 2022 +0000
Revision:
1:b30b99a74f6e
Parent:
0:0bda99bb39a4
sensor;

Who changed what in which revision?

UserRevisionLine numberNew contents of line
aralshukaili 0:0bda99bb39a4 1 #include "HCSR04.h"
aralshukaili 0:0bda99bb39a4 2 #include "mbed.h"
aralshukaili 0:0bda99bb39a4 3
aralshukaili 0:0bda99bb39a4 4
aralshukaili 0:0bda99bb39a4 5 HCSR04::HCSR04(PinName t, PinName e) : trig(t), echo(e) {}
aralshukaili 0:0bda99bb39a4 6
aralshukaili 0:0bda99bb39a4 7 // Trigger Echo
aralshukaili 0:0bda99bb39a4 8 // _______ _____________,,,,,,,,,
aralshukaili 0:0bda99bb39a4 9 // ____| 10us |_________| 150us-25ms, or 38ms if no obstacle
aralshukaili 0:0bda99bb39a4 10 //
aralshukaili 0:0bda99bb39a4 11
aralshukaili 0:0bda99bb39a4 12 //return echo duration in us (refer to digram above)
sas638 1:b30b99a74f6e 13 int HCSR04::echo_duration() {
aralshukaili 0:0bda99bb39a4 14 timer.reset();
sas638 1:b30b99a74f6e 15 trig = 0; //set trig low
sas638 1:b30b99a74f6e 16 wait_us(2); //wait 2 microseconds
sas638 1:b30b99a74f6e 17 trig = 1; //set trig high
sas638 1:b30b99a74f6e 18 wait_us(10); //wait 10 microseconds
sas638 1:b30b99a74f6e 19 trig = 0; // set trig low again
sas638 1:b30b99a74f6e 20 while(echo == 0); //while loop for starting timer when echo set to 0
sas638 1:b30b99a74f6e 21 timer.start(); //start timer
sas638 1:b30b99a74f6e 22 while(echo == 1); //while loop for stopping timer when echo set to 1
sas638 1:b30b99a74f6e 23 timer.stop(); // stop timer
sas638 1:b30b99a74f6e 24 return static_cast<int>(timer.read_us()); //return the timer
aralshukaili 0:0bda99bb39a4 25 }
aralshukaili 0:0bda99bb39a4 26
aralshukaili 0:0bda99bb39a4 27 //return distance to nearest obstacle or returns -1
aralshukaili 0:0bda99bb39a4 28 //if no obstacle within range
aralshukaili 0:0bda99bb39a4 29 //set sys to cm or inch accordingly
sas638 1:b30b99a74f6e 30 int HCSR04::distance(int sys){
aralshukaili 0:0bda99bb39a4 31 duration = echo_duration();
aralshukaili 0:0bda99bb39a4 32 if(duration > 30000)
aralshukaili 0:0bda99bb39a4 33 return -1;
aralshukaili 0:0bda99bb39a4 34 distacne_cm = duration /29 / 2 ;
aralshukaili 0:0bda99bb39a4 35 distance_inc = duration / 74 / 2;
aralshukaili 0:0bda99bb39a4 36 if (sys)
aralshukaili 0:0bda99bb39a4 37 return distacne_cm;
aralshukaili 0:0bda99bb39a4 38 else
aralshukaili 0:0bda99bb39a4 39 return distance_inc;
aralshukaili 0:0bda99bb39a4 40 }
aralshukaili 0:0bda99bb39a4 41