Program with explinations for ease of use of these Ultra-Sonic sensors to give mm resolution
main.cpp
- Committer:
- martinsimpson
- Date:
- 2017-03-16
- Revision:
- 1:221a6fd3d62f
- Parent:
- 0:2b4e5d360246
File content as of revision 1:221a6fd3d62f:
/*
Simple Program to use SFR05 or SFR04
Divide by 5.8 to give mm resolution from microseconds read of Echo pulse
Version 1.0b
M.Simpson 17/10/2016
*/
#include "mbed.h"
#define TRIGGER_PIN D8 //Connect your Ultra Sonic device to these pins
#define ECHO_PIN D7 //Modify for you platform used 'Arduino' Header on F401RE NUCLEO
DigitalOut Trigger(TRIGGER_PIN); //Instance of the DigitalOut class called 'Trigger'
DigitalIn Echo(ECHO_PIN); //Instance of the DigitalIn class called 'Echo'
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
Trigger=1; //Signal goes High i.e. 3V3
wait_us(100); //Wait 100us to give a pulse width
Trigger=0; //Signal goes Low i.e. 0V
pulse.reset(); //Rest the instance of the Timer Class
while(Echo==0&&EchoStart<25000){ //wait for Echo to go high
EchoStart=pulse.read_us(); //AND with timeout to prevent blocking!
}
while(Echo==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 return the value as a float
}