Library for controlling ultrasonic ranging module HCSR04 Ported by hiawoood from arduino library orgininally created by ITead studio.
HCSR04.cpp
- Committer:
- sas638
- Date:
- 2022-05-08
- Revision:
- 1:b30b99a74f6e
- Parent:
- 0:0bda99bb39a4
File content as of revision 1:b30b99a74f6e:
#include "HCSR04.h" #include "mbed.h" HCSR04::HCSR04(PinName t, PinName e) : trig(t), echo(e) {} // Trigger Echo // _______ _____________,,,,,,,,, // ____| 10us |_________| 150us-25ms, or 38ms if no obstacle // //return echo duration in us (refer to digram above) int HCSR04::echo_duration() { timer.reset(); trig = 0; //set trig low wait_us(2); //wait 2 microseconds trig = 1; //set trig high wait_us(10); //wait 10 microseconds trig = 0; // set trig low again while(echo == 0); //while loop for starting timer when echo set to 0 timer.start(); //start timer while(echo == 1); //while loop for stopping timer when echo set to 1 timer.stop(); // stop timer return static_cast<int>(timer.read_us()); //return the timer } //return distance to nearest obstacle or returns -1 //if no obstacle within range //set sys to cm or inch accordingly int HCSR04::distance(int sys){ duration = echo_duration(); if(duration > 30000) return -1; distacne_cm = duration /29 / 2 ; distance_inc = duration / 74 / 2; if (sys) return distacne_cm; else return distance_inc; }