Program with explinations for ease of use of these Ultra-Sonic sensors to give mm resolution

Dependencies:   mbed

main.cpp

Committer:
martinsimpson
Date:
2016-10-17
Revision:
0:2b4e5d360246
Child:
1:221a6fd3d62f

File content as of revision 0:2b4e5d360246:

/*
    Simple Program to use SFR05 or SFR04 in Single Pin Mode
    Divide by 5.8 to give mm resolution from microseconds read of Echo pulse
    Version 1.0a
    M.Simpson 17/10/2016
*/
#include "mbed.h"

DigitalInOut TriggerEcho(D8);                                   //Instance of the DigitalInOut class called 'TriggerEcho'

Timer pulse;                                                    //Instance of the Timer class called 'pulse'

float GetDistance();                                            //Function Prototype

int main() {
     float Distance;                                            //Assign a local variable for the main function
     pulse.start();                                             //Start the instance of the class timer        
     
     while(true)                                                //Continuous loop always true
     {
        Distance=GetDistance();                                 //Get the value returned from the function GetDistance()
        printf("Distance %.0fmm\n\r",Distance);                 //Send the value to the serial port for monitoring purposes
        wait_ms(250);                                           //Wait for 250ms
     }    
}
 
float GetDistance(){                                            //Function Name to be called
     int EchoPulseWidth=0,EchoStart=0,EchoEnd=0;                //Assign and set to zero the local variables for this function
     TriggerEcho.output();                                      //Make the DigitalInOut an Output to drive a signal
     TriggerEcho.write(1);                                      //Signal goes High i.e. 3V3
     wait_us(100);                                              //Wait 100us to give a pulse width
     TriggerEcho.write(0);                                      //Signal goes Low i.e. 0V
     TriggerEcho.input();                                       //Make the DigitalInOut an INPUT to accept a signal
     pulse.reset();                                             //Rest the instance of the Timer Class
     while(TriggerEcho.read()==0&&EchoStart<25000){             //wait for Echo to go high
            EchoStart=pulse.read_us();                          //AND with timeout to prevent blocking!      
     }
     while(TriggerEcho.read()==1&&(EchoEnd-EchoStart<25000)){   //wait for echo to return low
        EchoEnd=pulse.read_us();                                //or'd with timeout to prevent blocking!   
     }
     EchoPulseWidth=EchoEnd-EchoStart;                          //time period in us
     return (float)EchoPulseWidth/5.8f;                         //calculate distance in mm and reurn the value as a float
}