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.
Revision 0:b4a6f6bcab30, committed 2021-10-31
- Comitter:
- snapo
- Date:
- Sun Oct 31 10:46:33 2021 +0000
- Commit message:
- basic class for use of the HC-SR04 ultrasound sensor
Changed in this revision
| HC-SR04.cpp | Show annotated file Show diff for this revision Revisions of this file |
| HC-SR04.h | Show annotated file Show diff for this revision Revisions of this file |
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/HC-SR04.cpp Sun Oct 31 10:46:33 2021 +0000
@@ -0,0 +1,52 @@
+#include "HC-SR04.h"
+
+
+
+HCSR04::HCSR04 (PinName echo, PinName trigger):
+ echo_(echo), trigger_(trigger, PIN_OUTPUT, OpenDrain, 0){};
+
+void HCSR04::reading(){
+ t_.reset();
+
+ trigger_ = true;
+ wait_us(10);
+ trigger_ = false;
+
+ //waits for the echo pin to activate then starts to measure time
+ while(!echo_);
+ t_.start();
+ while(echo_);
+ //time stops being measured once echo is deactivated.
+ t_.stop();
+ //time measured in microseconds to increase the accuracy then the distance is scaled up into mm.
+ time_us_ = duration_cast<std::chrono::microseconds>(t_.elapsed_time()).count();
+ //distance stored in baseDistance_ variable
+ distance_ = (160*time_us_) / 1000;
+ thread_sleep_for(1000);
+}
+
+void HCSR04::fastTimeReading(){
+ t_.reset();
+
+ trigger_ = true;
+ wait_us(10);
+ trigger_ = false;
+
+ //waits for the echo pin to activate then starts to measure time
+ while(!echo_);
+ t_.start();
+ while(echo_);
+ //time stops being measured once echo is deactivated.
+ t_.stop();
+ time_us_ = duration_cast<std::chrono::microseconds>(t_.elapsed_time()).count();
+
+}
+
+int HCSR04::getTime(){
+ return time_us_;
+}
+
+int HCSR04::getDistance(){
+ return distance_;
+}
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/HC-SR04.h Sun Oct 31 10:46:33 2021 +0000
@@ -0,0 +1,24 @@
+#pragma once
+#include "mbed.h"
+
+
+class HCSR04 {
+ DigitalIn echo_ ;
+ DigitalInOut trigger_;
+
+ Timer t_;
+ int time_us_;
+ int distance_;
+
+
+public:
+
+ HCSR04(PinName echo, PinName trigger);
+
+ void reading();
+ void fastTimeReading();
+
+ int getTime();
+ int getDistance();
+
+};
\ No newline at end of file