Solution to CS 220 Lab 4. Includes a "device driver" for the HCSR04.

Dependencies:   TextLCD mbed

Revision:
0:cb8c03115a57
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Mon Jun 26 15:32:21 2017 +0000
@@ -0,0 +1,55 @@
+#include "mbed.h"
+#include "TextLCD.h"
+
+float measure();
+
+int main()
+{
+
+    TextLCD lcd(PTE30, PTE29, PTE23, PTE22, PTE21, PTE20); // rs, e, d4-d7
+    float distance;
+
+    while(1) {
+        distance = measure();
+        lcd.cls();
+        lcd.printf("Distance = %.2f in.", distance);
+        wait(0.5);
+    }
+}
+
+// HCSR04 "driver"
+float measure()
+{
+    Timer timer;
+    long time;
+    DigitalOut trigger(PTB9);
+    DigitalIn echo(PTB8);
+
+    timer.reset();
+
+    // Ensure HCSR04 is idle.
+    trigger = 0;
+    wait (0.060);
+
+    // Trigger the HCSR04.
+    trigger = 1;
+    wait_us(10);
+    trigger = 0;
+
+    // Wait for the HCSR04's measurement cycle to begin.
+    while (echo == 0)
+        ;
+
+    // Start measuring.
+    timer.start();
+    while (echo == 1)
+        ;
+    timer.stop();
+
+    time = timer.read_us();
+
+    if (time > 30000) // Delay at maximum range plus some slop.
+        return -1.0;   // Didn't receive an echo.
+    else
+        return 0.006756 * time;
+}
\ No newline at end of file