Ultrasonic sensor used HC-SR04

Dependencies:   mbed

Revision:
0:6947b0547f9f
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Sun Jan 18 13:42:41 2015 +0000
@@ -0,0 +1,34 @@
+#include "mbed.h"
+
+Serial pc(USBTX,USBRX);
+DigitalOut trig(p21);
+DigitalOut testled(LED1);
+DigitalIn echo(p22);
+Timer t;
+#define sonic_spead 343.595*100;// cm
+
+int main() {
+    double time;
+    while(1) {
+        testled = 0;
+        t.reset();
+        trig = 1;
+        time = 0;
+        wait_us(10);
+        trig = 0;
+        if (echo == 1) {
+            t.start();
+            while(1){
+                if(echo == 0) {
+                    testled = 1;
+                    t.stop();
+                    time = t.read();
+                    time = time / 2.0 *sonic_spead;
+                    pc.printf("%lfcm\n\r",time);
+                    t.reset();
+                    break;
+                }
+            }
+        }
+    }
+}