Working ultrasonic (sample).
Dependents: ROCO104_Buggy BuggyDesign
UltraSonic.cpp
00001 #include "mbed.h" 00002 #include "UltraSonic.h" 00003 00004 DigitalOut Trigger(D7); //Instance of the DigitalInOut class called 'TriggerEcho' WAS D6 00005 DigitalIn Echo(D2); //Instance of the DigitalInOut class called 'TriggerEcho' 00006 Timer pulse; //Instance of the Timer class called 'pulse' so we can measure timed events 00007 00008 00009 // Function ultra_sonic_distance() will load the global variable distance with Ultra Sonic Sensor value in mm 00010 // and then send the value to the stdio ouput i.e serial over USB 00011 void ultra_sonic_distance(void) 00012 { 00013 printf("%dmm \n\r",(int)GetDistance()); 00014 } 00015 00016 // Function GetDistance() will return a float value of the Distance from the Ultrasonic Sensor in millimetres typically use as: ‘(float)myDistance=GetDistance();’ 00017 float GetDistance() 00018 { //Function Name to be called 00019 int EchoPulseWidth=0,EchoStart=0,EchoEnd=0; //Assign and set to zero the local variables for this function 00020 Trigger = 1; //Signal goes High i.e. 3V3 00021 wait_us(100); //Wait 100us to give a pulse width Triggering the Ultrasonic Module 00022 Trigger = 0; //Signal goes Low i.e. 0V 00023 pulse.start(); //Start the instance of the class timer 00024 pulse.reset(); //Reset the instance of the Timer Class 00025 while(Echo == 0 && EchoStart < 25000){ //wait for Echo to go high 00026 EchoStart=pulse.read_us(); //Conditional 'AND' with timeout to prevent blocking! 00027 } 00028 while(Echo == 1 && ((EchoEnd - EchoStart) < 25000)){//wait for echo to return low 00029 EchoEnd=pulse.read_us(); //Conditional 'OR' with timeout to prevent blocking! 00030 } 00031 EchoPulseWidth = EchoEnd - EchoStart; //time period in us 00032 pulse.stop(); //Stop the instance of the class timer 00033 return (float)EchoPulseWidth/5.8f; //calculate distance in mm and return the value as a float 00034 } 00035 00036
Generated on Wed Jul 13 2022 15:50:58 by
1.7.2