Development and testing of ultrasonic distance measurement library for device HC-SR04.
Dependencies: TextLCD_improved mbed Distance_HC_SR04
Diff: main.cpp
- Branch:
- CLASS_IMPLEMENTATION
- Revision:
- 2:aba8d0d53190
- Parent:
- 0:6fd0fbcfc7e1
- Child:
- 3:cb5931861f4e
--- a/main.cpp Sun Dec 20 21:24:00 2015 +0000 +++ b/main.cpp Sun Dec 20 21:24:45 2015 +0000 @@ -9,6 +9,11 @@ #define CALC_COEFF (1000.0f*340.0f/2) #define TICKS_RANGE_MAX (15000) #define TICKS_RANGE_MIN (150) +#define TRIG_PULSE_US (500) + + +typedef enum { IDLE, STARTED, COMPLETED, TIMEOUT, OUT_OF_RANGE_MIN, OUT_OF_RANGE_MAX, ERROR_SIG } Distance_HC_SR04_state; + TextLCD lcd(PA_8, PA_7, PA_9, PA_1, PB_5, PA_10, TextLCD::LCD16x2); @@ -23,13 +28,136 @@ static Timeout timeout; -static volatile enum { IDLE, STARTED, COMPLETED, TIMEOUT, OUT_OF_RANGE_MIN, OUT_OF_RANGE_MAX, ERROR_SIG } state; +static volatile Distance_HC_SR04_state state; void tout(void) { if (state == STARTED) state = TIMEOUT; } + +class Distance_HC_SR04 { +public: + Distance_HC_SR04(PinName trig, PinName echo, uint32_t tout_us = TIMEOUT_DELAY_US, float coeff = CALC_COEFF) : _trig(trig), _echo(echo), _tout_us(tout_us), _coeff(coeff) { + _trig = 0; + _state = IDLE; + } + + void trigger(void) { + if (_state == IDLE && _echo == 0) { + _timeout.detach(); + _timer.stop(); + _timer.reset(); + + _trig = 1; + wait_us(TRIG_PULSE_US); + _trig = 0; + + if (_echo == 0) { + _state = STARTED; + timeout.attach_us(this, &Distance_HC_SR04::_tout, TIMEOUT_DELAY_US); + + _echo.rise(this, &Distance_HC_SR04::_rising); + _echo.fall(this, &Distance_HC_SR04::_falling); + + return; + } + } + + if (_state == IDLE) { + _state = ERROR_SIG; + _ticks_us = 0; + } + + return; + } + + Distance_HC_SR04_state getState(void) { + return _state; + } + + void reset(void) { + _state = IDLE; + _echo.rise(NULL); + _echo.fall(NULL); + _timeout.detach(); + _timer.stop(); + _timer.reset(); + } + + uint32_t getTicks(void) { + return _ticks_us; + } + + float getDistance(void) { + return _ticks_us/_coeff; + } + + float getCoeff(void) { + return _coeff; + } + + void setCoeff(float coeff) { + _coeff = coeff; + } + + float measureDistance(void) { + return measureTicks()/_coeff; + } + + uint32_t measureTicks(void) { + reset(); + trigger(); + + while (_state == STARTED) + ; + + switch (_state) { + case COMPLETED: + break; + default: + break; + } + + return _ticks_us; + } + + + + void _tout(void) { + if (_state == STARTED) + _state = TIMEOUT; + } + + void _rising(void) { + if (_state == STARTED) { + _timer.start(); + } + } + + void _falling(void) { + if (_state == STARTED) { + _timer.stop(); + _ticks_us = _timer.read_us(); + state = COMPLETED; + } + } + +private: + DigitalOut _trig; + InterruptIn _echo; + uint32_t _ticks_us; + uint32_t _tout_us; + float _coeff; + + Timer _timer; + Timeout _timeout; + + volatile Distance_HC_SR04_state _state; +}; + + + int main() { trigDist = 0;