Synchronous and asynchronous library for ultrasonic distance measurement for the device HC-SR04 with error handling functionality (out of range detection, HW error detection). Main features: "echo" puls duration measurement, distance measurement from "echo" pulse duration, detection of "echo" signal malfunction, timeout detection, detection of measured values outside reliable limits (min, max)

Dependents:   TEST_Dist_lib

Distance_HC_SR04.h

Committer:
dzoni
Date:
2015-12-21
Revision:
0:4fbf332e6759
Child:
4:71f01fbc9246

File content as of revision 0:4fbf332e6759:

#ifndef MBED_DISTANCE_HC_SR04_H
#define MBED_DISTANCE_HC_SR04_H
 
#include "mbed.h"
 
#define TIMEOUT_DELAY_US    (25000)
#define CALC_COEFF          (340.0f/(2.0f*1000.0f))
#define TICKS_RANGE_MAX     (15000)
#define TICKS_RANGE_MIN     (150)
#define TRIG_PULSE_US       (50)

typedef enum { IDLE, STARTED, COMPLETED, TIMEOUT, OUT_OF_RANGE_MIN, OUT_OF_RANGE_MAX, ERROR_SIG } Distance_HC_SR04_state;

/** Distance_HC_SR04 class.
 *
 *  Library for interfacing ultrasonic distance measurement device HC-SR04.
 *  Functionality includes detection of error in echo signal, detection of timeout and limits of reliable measurement.
 *
 */
class Distance_HC_SR04 {

public:
    Distance_HC_SR04(PinName trig, PinName echo, uint32_t tout_us = TIMEOUT_DELAY_US, float coeff = CALC_COEFF,
            uint32_t tmin_us = TICKS_RANGE_MIN, uint32_t tmax_us = TICKS_RANGE_MAX);
    void trigger(void);
    Distance_HC_SR04_state getState(void);
    void reset(void);
    uint32_t getTicks(void);
    float getDistance(void);
    float getCoeff(void);
    void setCoeff(float coeff);
    float measureDistance(void);
    uint32_t measureTicks(void);

    void _tout(void);
    void _rising(void);
    void _falling(void);

private:
    DigitalOut  _trig;
    InterruptIn _echo;
    uint32_t    _tout_us;
    float       _coeff;
    uint32_t    _tmin_us;
    uint32_t    _tmax_us;

    Timer       _timer;
    Timeout     _timeout;

    volatile Distance_HC_SR04_state _state;
    uint32_t                        _ticks_us;
};
 
#endif