Sakis Kasampalis
/
ultrasonic-finder
Using an SR04
ultrasonic-finder.cpp
- Committer:
- faif
- Date:
- 2016-12-18
- Revision:
- 0:6f74064686e4
File content as of revision 0:6f74064686e4:
#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); }