Using an SR04

Dependencies:   mbed

Files at this revision

API Documentation at this revision

Comitter:
faif
Date:
Sun Dec 18 00:31:29 2016 +0000
Commit message:
First version

Changed in this revision

mbed.bld Show annotated file Show diff for this revision Revisions of this file
ultrasonic-finder.cpp Show annotated file Show diff for this revision Revisions of this file
ultrasonic-finder.h Show annotated file Show diff for this revision Revisions of this file
diff -r 000000000000 -r 6f74064686e4 mbed.bld
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed.bld	Sun Dec 18 00:31:29 2016 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/users/mbed_official/code/mbed/builds/faff56e089b2
\ No newline at end of file
diff -r 000000000000 -r 6f74064686e4 ultrasonic-finder.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/ultrasonic-finder.cpp	Sun Dec 18 00:31:29 2016 +0000
@@ -0,0 +1,60 @@
+#include "mbed.h"
+#include "ultrasonic-finder.h"
+
+static const char CLS[] = "\x1B[2J";        // VT100 erase screen
+static const char HOME[] = "\x1B[H";        // VT100 home
+static const int delay = 2;
+
+static const float pulse_line = 4E-5;       // 40 ns
+static const int pulse_to_distance = 58;    // 617 / 10.6
+
+enum
+{
+    DOWN = 0,
+    UP = 1
+};
+
+int main() 
+{
+    clear_screen();
+    
+    Timer timer;
+    timer.start();
+    
+    while (true) 
+    {
+        send_pulse(trigger);
+        while (!echo) {};                  // wait for echo
+        float pulse = measure_pulse(timer, echo);
+        show_result(pulse);
+        wait(delay);
+    }        
+}
+
+void clear_screen()
+{
+    pc.printf(CLS);      
+    pc.printf(HOME);               
+}
+
+void send_pulse(DigitalOut& triggerOut)
+{
+    triggerOut = UP;
+    wait(pulse_line);
+    triggerOut = DOWN;
+}
+
+float measure_pulse(Timer& timer, const DigitalIn& echoIn)
+{
+    timer.reset();
+    while (echo) {};
+    return timer.read_us();
+}
+
+void show_result(float pulse)
+{
+    pc.printf(HOME);    
+    pc.printf("Pulse length %6.0f uS\n\r", pulse);
+    pulse /= pulse_to_distance;
+    pc.printf("\n\rDistance %4.0f cm\n\r", pulse);
+}
\ No newline at end of file
diff -r 000000000000 -r 6f74064686e4 ultrasonic-finder.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/ultrasonic-finder.h	Sun Dec 18 00:31:29 2016 +0000
@@ -0,0 +1,13 @@
+#ifndef ULTRASONIC_FINDER_H
+#define ULTRASONIC_FINDER_H
+
+DigitalIn echo(p20);
+DigitalOut trigger(p19);
+Serial pc(USBTX, USBRX);
+
+void clear_screen();
+void send_pulse(DigitalOut& triggerOut);
+float measure_pulse(Timer& timer, const DigitalIn& echoIn);
+void show_result(float pulse);
+
+#endif
\ No newline at end of file