Program using a HC-SR04 Ultrasonic sensor.

Dependencies:   mbed

Fork of Ultrasonico_HC-SR04 by Icaro Brito

Just a translation to english, used for Youth club of electronic in Roznov

main.cpp

Committer:
b34196
Date:
2017-12-20
Revision:
1:ad8ec262e808
Parent:
0:34f7d9ef2f4b

File content as of revision 1:ad8ec262e808:

/* Program for Ultrasonic sensor use
*/
/*Pin interruptions are only possible with ports A and D*/

#include "mbed.h"

 Serial pc(USBTX,USBRX);  //Configuration of the serial communication to send the value of the sensor
 DigitalOut trig(PTE3,0);  //Trigger pin configuration
 InterruptIn echo(PTA16);   //Echo pin interrupt configuration
 Timer tempo;
 float tdist=0, distcm=0, distin=0, dist0=0;

    void iniP(){            //Routine to receive the initial pulse of the Echo pin
        tempo.start();      //Routine to start the counter
        return;
        }
        
    void finP(){ //Routine to get the end time of the pulse
    
        tdist = tempo.read_us();  //Reading the elapsed time
        distcm = tdist/58;         // distance "cm"
        distin = tdist/148;        // distance "in"
        
        tempo.stop();           //Stop the timer
        tempo.reset();          //reset to next cycle
        return;
        }
        
        
        
    int main(){
        printf("Ultrasonic ranging test \n"); 
        while(1){
            
            trig=1;             //trigger start
            wait_us(10);        // 10us puls
            trig=0;             //end of trigger
            
            echo.rise(&iniP);   //return pulse start reading
            echo.fall(&finP);   //Reading the end of the return pulse
            
            if(distcm != dist0){ //routine to avoid sending too many values
                dist0 = distcm;
                printf("Distance detected by sensor %.2f cm \r\n",distcm); 
            }
           wait_ms(60);     //routine to prevent the trigger pulse from being confused with the "echo"           
        }
             
         
    }