A library for the HCSR04 sensor. work with interrupt

Dependents:   AdrianLysShow AdrianLysShow

A small library for the HCSR04 sensor. works with interrupt on the egde of the echo

link to datasheet: http://www.micropik.com/PDF/HCSR04.pdf

Files at this revision

API Documentation at this revision

Comitter:
gert_lauritsen
Date:
Tue Apr 28 14:46:20 2015 +0000
Child:
1:e3a37f4015da
Commit message:
Working version of distance sensor; works with interrupt measuring the time of fligth

Changed in this revision

HCSR04.cpp Show annotated file Show diff for this revision Revisions of this file
HCSR04.h Show annotated file Show diff for this revision Revisions of this file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/HCSR04.cpp	Tue Apr 28 14:46:20 2015 +0000
@@ -0,0 +1,33 @@
+#include "HCSR04.h"
+#include "mbed.h"
+#define DistanceOffset 180
+HCSR04::HCSR04(PinName t, PinName e,callback_type _callback) : trig(t), echo(e) 
+{
+ echo.rise(this, &HCSR04::StartTimer); 
+ echo.fall(this, &HCSR04::DistResult);
+ pulsWidth=new Timeout; 
+ callback = _callback;     
+}
+
+void HCSR04::StartTimer() {
+   timer.reset();
+   timer.start(); 
+}
+
+void HCSR04::DistResult() {
+//Getting the distance
+ dist_cm =timer.read_us()-DistanceOffset;
+ callback(dist_cm*0.034);   //time the speed of sound
+}
+
+void HCSR04::Trigoff() {
+    trig = 0;
+}
+
+void HCSR04::Trigger() {
+//Makes a trigger signal
+    trig = 1;
+    pulsWidth->attach_us(this,&HCSR04::Trigoff,10);
+    //Give it 10 us puls
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/HCSR04.h	Tue Apr 28 14:46:20 2015 +0000
@@ -0,0 +1,40 @@
+//---------------------------------------------------------
+//Class for measure distance with the HCSR04 sensor
+/*
+Eksemple
+void distance(long Duration) {
+      //  long distance = sensor.distance(1);
+        printf("Distance: %d   \r",Duration);    
+}
+
+int main()
+{
+    sensor= new HCSR04(p5,p6,distance); 
+    printf("Test af sensor\r\n");
+    while(1) {
+       sensor->Trigger();
+       wait(0.1); 
+
+    }
+}
+*/
+#include "mbed.h"
+typedef void (*callback_type)(long); 
+ 
+class HCSR04 {
+  public:
+    HCSR04(PinName t, PinName e,callback_type _callback);
+    void Trigger(); //starts the trigger
+    
+    private:
+        DigitalOut trig;
+        InterruptIn echo;
+        Timer timer;
+        Timeout *pulsWidth;
+        callback_type callback;
+        long dist_cm;
+        
+        void Trigoff(); //Turnoff the trigger
+        void DistResult();
+        void StartTimer(); 
+};
\ No newline at end of file