Development and testing of ultrasonic distance measurement library for device HC-SR04.
Dependencies: TextLCD_improved mbed Distance_HC_SR04
Diff: Distance_HC_SR04.h
- Branch:
- CLASS_IMPLEMENTATION
- Revision:
- 5:1a69f40177b0
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Distance_HC_SR04.h Mon Dec 21 20:54:09 2015 +0000 @@ -0,0 +1,54 @@ +#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 \ No newline at end of file