Tom Kelliher
/
RangeFinder
Solution to CS 220 Lab 4. Includes a "device driver" for the HCSR04.
main.cpp
- Committer:
- tpkelliher
- Date:
- 2017-06-26
- Revision:
- 0:cb8c03115a57
File content as of revision 0:cb8c03115a57:
#include "mbed.h" #include "TextLCD.h" float measure(); int main() { TextLCD lcd(PTE30, PTE29, PTE23, PTE22, PTE21, PTE20); // rs, e, d4-d7 float distance; while(1) { distance = measure(); lcd.cls(); lcd.printf("Distance = %.2f in.", distance); wait(0.5); } } // HCSR04 "driver" float measure() { Timer timer; long time; DigitalOut trigger(PTB9); DigitalIn echo(PTB8); timer.reset(); // Ensure HCSR04 is idle. trigger = 0; wait (0.060); // Trigger the HCSR04. trigger = 1; wait_us(10); trigger = 0; // Wait for the HCSR04's measurement cycle to begin. while (echo == 0) ; // Start measuring. timer.start(); while (echo == 1) ; timer.stop(); time = timer.read_us(); if (time > 30000) // Delay at maximum range plus some slop. return -1.0; // Didn't receive an echo. else return 0.006756 * time; }