A simple PWM decoder class. It is based on using 2 interrupts, one for rising and another for falling edges of the input pulse. This is a very simple approach, possibly accurate enough to decode RC receiver pulses.
Revision 0:b0ec6b86deaa, committed 2016-05-15
- Comitter:
- salarian
- Date:
- Sun May 15 11:08:46 2016 +0000
- Commit message:
- Initial commit
Changed in this revision
pulse_decoder.cpp | Show annotated file Show diff for this revision Revisions of this file |
pulse_decoder.h | Show annotated file Show diff for this revision Revisions of this file |
diff -r 000000000000 -r b0ec6b86deaa pulse_decoder.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/pulse_decoder.cpp Sun May 15 11:08:46 2016 +0000 @@ -0,0 +1,27 @@ +#include "mbed.h" +#include "pulse_decoder.h" + +pulse_decoder::pulse_decoder(PinName pin) + : interrupt(pin), high_period(0), low_period(false) +{ + interrupt.rise(this, &pulse_decoder::rising_edge); + interrupt.fall(this, &pulse_decoder::falling_edge); +} + +void pulse_decoder::rising_edge() +{ + high_timer.start(); + low_timer.stop(); + + low_period = low_timer.read_us(); + low_timer.reset(); +} + +void pulse_decoder::falling_edge() +{ + high_timer.stop(); + low_timer.start(); + + high_period = high_timer.read_us(); + high_timer.reset(); +}
diff -r 000000000000 -r b0ec6b86deaa pulse_decoder.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/pulse_decoder.h Sun May 15 11:08:46 2016 +0000 @@ -0,0 +1,56 @@ +#ifndef PULSE_DECODER_H +#define PULSE_DECODER_H + +/// @file pulse_decoder.h This library provides a simple PWM decoder class. +/// +/// The approach is based on installing two interrupt routines for the rising and +/// falling edges of an input pin and measuring the time between the two events. +/// +/// Example: +/// @code +/// #include "mbed.h" +/// void main() +/// { +/// pulse_decoder pulse(D7); +/// +/// while(true) { +/// printf("Pulse high = %5d low = %5d (us) Period = %5d\n", +/// pulse.get_high_period(), pulse.get_low_period(), +/// pulse.get_high_period() + pulse.get_low_period()); +/// wait(.2); +/// } +/// } +/// @endcode + +class pulse_decoder { +public: + ///Creates a pulse_decoder + ///@param[in] pin the input pin on the microcontroller + pulse_decoder(PinName pin); + + ///Get the period of time that the pulse was in high state + ///@return the period in us + int get_high_period() const + { + return high_period; + } + + ///Get the period of time that the pulse was in low state + ///@return the period in us + int get_low_period() const + { + return low_period; + } + +private: + InterruptIn interrupt; + Timer high_timer; + Timer low_timer; + volatile int high_period; + volatile int low_period; + + void rising_edge(); + void falling_edge(); +}; + +#endif //PULSE_DECODER_H \ No newline at end of file