Sakis Kasampalis
/
ultrasonic-finder
Using an SR04
Embed:
(wiki syntax)
Show/hide line numbers
ultrasonic-finder.cpp
00001 #include "mbed.h" 00002 #include "ultrasonic-finder.h" 00003 00004 static const char CLS[] = "\x1B[2J"; // VT100 erase screen 00005 static const char HOME[] = "\x1B[H"; // VT100 home 00006 static const int delay = 2; 00007 00008 static const float pulse_line = 4E-5; // 40 ns 00009 static const int pulse_to_distance = 58; // 617 / 10.6 00010 00011 enum 00012 { 00013 DOWN = 0, 00014 UP = 1 00015 }; 00016 00017 int main() 00018 { 00019 clear_screen(); 00020 00021 Timer timer; 00022 timer.start(); 00023 00024 while (true) 00025 { 00026 send_pulse(trigger); 00027 while (!echo) {}; // wait for echo 00028 float pulse = measure_pulse(timer, echo); 00029 show_result(pulse); 00030 wait(delay); 00031 } 00032 } 00033 00034 void clear_screen() 00035 { 00036 pc.printf(CLS); 00037 pc.printf(HOME); 00038 } 00039 00040 void send_pulse(DigitalOut& triggerOut) 00041 { 00042 triggerOut = UP; 00043 wait(pulse_line); 00044 triggerOut = DOWN; 00045 } 00046 00047 float measure_pulse(Timer& timer, const DigitalIn& echoIn) 00048 { 00049 timer.reset(); 00050 while (echo) {}; 00051 return timer.read_us(); 00052 } 00053 00054 void show_result(float pulse) 00055 { 00056 pc.printf(HOME); 00057 pc.printf("Pulse length %6.0f uS\n\r", pulse); 00058 pulse /= pulse_to_distance; 00059 pc.printf("\n\rDistance %4.0f cm\n\r", pulse); 00060 }
Generated on Tue Jul 12 2022 19:22:39 by 1.7.2