create

Dependents:   Nucleo_UltrasonicHelloWorld

Fork of HCSR04 by Antoniolinux B.

Committer:
ryuhs74
Date:
Mon Aug 10 01:02:07 2015 +0000
Revision:
1:a6912eacfb20
Parent:
0:86b2086be101
z

Who changed what in which revision?

UserRevisionLine numberNew contents of line
antoniolinux 0:86b2086be101 1 #include "hcsr04.h"
antoniolinux 0:86b2086be101 2 #include "mbed.h"
antoniolinux 0:86b2086be101 3 /*
antoniolinux 0:86b2086be101 4 *HCSR04.cpp
antoniolinux 0:86b2086be101 5 */
antoniolinux 0:86b2086be101 6 HCSR04::HCSR04(PinName t, PinName e) : trig(t), echo(e) {}
ryuhs74 1:a6912eacfb20 7
ryuhs74 1:a6912eacfb20 8 long HCSR04::echo_duration() {
antoniolinux 0:86b2086be101 9 timer.reset(); //reset timer
antoniolinux 0:86b2086be101 10 trig=0; // trigger low
antoniolinux 0:86b2086be101 11 wait_us(2); // wait
antoniolinux 0:86b2086be101 12 trig=1; // trigger high
antoniolinux 0:86b2086be101 13 wait_us(10);
antoniolinux 0:86b2086be101 14 trig=0; // trigger low
ryuhs74 1:a6912eacfb20 15
ryuhs74 1:a6912eacfb20 16 while(!echo); // start pulseIN
ryuhs74 1:a6912eacfb20 17 timer.start();
ryuhs74 1:a6912eacfb20 18
ryuhs74 1:a6912eacfb20 19 while(echo);
ryuhs74 1:a6912eacfb20 20 timer.stop();
ryuhs74 1:a6912eacfb20 21 return timer.read_us();
antoniolinux 0:86b2086be101 22 }
ryuhs74 1:a6912eacfb20 23
antoniolinux 0:86b2086be101 24 //return distance in cm
antoniolinux 0:86b2086be101 25 long HCSR04::distance(){
antoniolinux 0:86b2086be101 26 duration = echo_duration();
ryuhs74 1:a6912eacfb20 27 distance_cm = (duration/2)/29.1 ;
ryuhs74 1:a6912eacfb20 28 return distance_cm;
antoniolinux 0:86b2086be101 29 }