test of us sensor
Dependencies: HC_SR04_Ultrasonic_Library mbed
Fork of Nucleo_UltrasonicHelloWorld by
Revision 2:174ac1a5a658, committed 2018-02-09
- Comitter:
- fjwats
- Date:
- Fri Feb 09 16:22:57 2018 +0000
- Parent:
- 1:4a5586eb1765
- Commit message:
- testHCSR04 us sensor
Changed in this revision
| main.cpp | Show annotated file Show diff for this revision Revisions of this file |
--- a/main.cpp Thu Dec 04 08:04:55 2014 +0000
+++ b/main.cpp Fri Feb 09 16:22:57 2018 +0000
@@ -1,23 +1,65 @@
#include "mbed.h"
-#include "ultrasonic.h"
-
- void dist(int distance)
-{
- //put code here to happen when the distance is changed
- printf("Distance changed to %dmm\r\n", distance);
-}
-
-ultrasonic mu(D8, D9, .1, 1, &dist); //Set the trigger pin to D8 and the echo pin to D9
- //have updates every .1 seconds and a timeout after 1
- //second, and call dist when the distance changes
-
+
+DigitalOut trigger(p13);
+DigitalOut myled(LED1); //monitor trigger
+DigitalOut myled2(LED2); //monitor echo
+DigitalOut myled3(LED3);
+DigitalOut myled4(LED4);
+DigitalIn echo(p14);
+int distance = 0;
+int correction = 0;
+Timer sonar;
+
int main()
{
- mu.startUpdates();//start mesuring the distance
- while(1)
- {
- //Do something else here
- mu.checkDistance(); //call checkDistance() as much as possible, as this is where
- //the class checks if dist needs to be called.
+ sonar.reset();
+// measure actual software polling timer delays
+// delay used later in time correction
+// start timer
+ sonar.start();
+// min software polling delay to read echo pin
+ while (echo==2) {};
+ myled2 = 0;
+// stop timer
+ sonar.stop();
+// read timer
+ correction = sonar.read_us();
+ printf("Approximate software overhead timer delay is %d uS\n\r",correction);
+
+//Loop to read Sonar distance values, scale, and print
+ while(1) {
+// trigger sonar to send a ping
+ trigger = 1;
+ myled = 1;
+ myled2 = 0;
+ sonar.reset();
+ wait_us(10.0);
+ trigger = 0;
+ myled = 0;
+//wait for echo high
+ while (echo==0) {};
+ myled2=echo;
+//echo high, so start timer
+ sonar.start();
+//wait for echo low
+ while (echo==1) {};
+//stop timer and read value
+ sonar.stop();
+//subtract software overhead timer delay and scale to cm
+ distance = (sonar.read_us()-correction)/58.0;
+ myled2 = 0;
+ printf(" %d cm \n\r",distance);
+
+ if (distance<10) {
+ myled3= 1;
+ }
+ if (distance>=10) {
+ myled4= 1;
+ }
+
+
+//wait so that any echo(s) return before sending another ping
+ wait(0.2);
+ myled3 = myled4 = 0;
}
-}
+}
\ No newline at end of file
