Sakis Kasampalis
/
ultrasonic-finder
Using an SR04
Diff: ultrasonic-finder.cpp
- Revision:
- 0:6f74064686e4
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