Sam Walsh / HCSR04

Fork of HCSR04 by Antoniolinux B.

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers hcsr04.cpp Source File

hcsr04.cpp

00001 #include "hcsr04.h"
00002 #include "mbed.h"
00003 /*
00004 *HCSR04.cpp
00005 */
00006 HCSR04::HCSR04(PinName t, PinName e) : trig(t), echo(e) {}
00007  long HCSR04::echo_duration() {
00008         
00009     timer.reset();  //reset timer
00010     timeout_timer.reset();
00011     
00012     //Initiate Trigger
00013     trig=0;   // trigger low 
00014     wait_us(2); //  wait 
00015     trig=1;   //  trigger high
00016     wait_us(10);
00017     trig=0;  // trigger low
00018     
00019     timeout_timer.start();
00020     
00021     while(!echo){
00022       //Wait for 5V/3.3V pulse to start
00023       if(timeout_timer.read_ms()>=10){ //100 ms timeout
00024           timedOut = true;
00025           break;      
00026           }
00027       }
00028       
00029       //Pulse Started
00030       if(timedOut == true){
00031           //Error, pulse didn't start for some reason
00032           timedOut = false;
00033           return 999999;  //error pulse not started in time
00034       }
00035       else
00036       {
00037         timeout_timer.reset();
00038         timer.start();
00039         timeout_timer.start(); 
00040         while(echo){
00041             if(timeout_timer.read_ms()>=10){
00042                 timedOut = true;
00043                 break;
00044             }        
00045         }
00046         if(timedOut == true){
00047           timedOut = false;
00048           return 999999;
00049           }
00050         else{
00051           timer.stop();
00052           return timer.read_us();     
00053           }  
00054       }
00055       
00056       
00057       
00058 
00059  
00060 }
00061  
00062 //return distance in cm 
00063 long HCSR04::distance(){
00064     duration = echo_duration();
00065   distance_cm = (duration/2)/29.1  ;
00066         return distance_cm;
00067 
00068 }