A program that demonstrates the development of library, using as an example an ultrasonic distance sensor HC-SR04.

Dependencies:   mbed HCSR04 AutomationElements

main.cpp

Committer:
tbjazic
Date:
2015-12-03
Revision:
0:ebee649c5b1b
Child:
1:22043b67c31c

File content as of revision 0:ebee649c5b1b:

/** Initial test of the ultrasonic sensor HC-SR04  */

#include "mbed.h"

Serial pc(USBTX, USBRX);    // communication with terminal
InterruptIn echo(p5);       // echo pin
DigitalOut trigger(p7);     // trigger pin
Timer timer;                // echo pulsewidth measurement

/** Start the echo pulsewidth measurement */
void startTimer() {
    timer.start(); // start the timer
}

/** Stop the echo pulsewidth measurement */
void stopTimer() {
    timer.stop(); // stop the timer
}

int main() {
    /** configure the rising edge to start the timer */
    echo.rise(&startTimer);
    
    /** configure the falling edge to stop the timer */
    echo.fall(&stopTimer);
    
    while(1) {
        /** Start the measurement by sending the 10us trigger pulse */
        trigger = 1;
        wait_us(10);
        trigger = 0;
        
        /** Wait for the sensor to finish measurement (generate rise and fall interrupts).
         *  Minimum wait time is determined by maximum measurement distance of 400 cm.
         *  t_min = 400 * 58 = 23200 us = 23.2 ms */
        wait(1); 
        
        /** calculate the distance in cm */
        float distance = timer.read() * 1e6 / 58;
        timer.reset(); // reset the timer to 0
        
        /** Print the result in cm to the terminal with 1 decimal place
         *  (number 5 after % means that total of 5 digits will be reserved
         *  for printing the number, including the dot and one decimal place). */
        pc.printf("Distance: %5.1f cm\r", distance);
    }
}