Chris Powers / Mbed 2 deprecated YT_001_HCSR04

Dependencies:   mbed

Revision:
0:777a2656a150
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Wed Jun 03 15:31:47 2020 +0000
@@ -0,0 +1,58 @@
+#include "mbed.h"
+// Trigger PIN
+DigitalOut trigger(D9);
+// Echo PIN
+DigitalIn echo(D8);
+// Serial connection
+Serial pc(USBTX, USBRX, 115200);
+// Timer to get the time between the 
+Timer get_time;
+
+// Prototyping
+float sensor(void);
+
+// Function will return distance in cm
+float sensor(void)
+{
+    float distance;
+    
+    // Send HIGH for 10 us to start measurement
+    trigger.write(1);
+    wait_us(10);
+    trigger.write(0);
+    // Wait for the ECHO to change to HIGH
+    while(echo.read() == 0) {}
+    // Start the timer and let it run until ECHO is LOW again
+    get_time.reset();
+    get_time.start();
+    while(echo.read() == 1) {}
+    get_time.stop();
+    // Calculate the distance from the time in microseconds
+    distance = get_time.read_us();
+    distance = distance * 0.03432f / 2.0f;
+    
+    return distance;
+    
+}
+
+
+int main(void)
+{
+    // Set the trigger output to LOW at the start of the programm
+    trigger = 0;
+    // Welcome text
+    pc.printf("\nHC-SR04 Sensor\n");
+
+    // Main loop to measure the distance
+    while(1)
+    {
+        wait(0.5);
+        // Print the actual distance to the serial output
+        pc.printf("Distance: %.2fcm \n", sensor());
+        
+    }
+    
+    return 0;
+}
+
+