Interface with a single channel encoder (eg IR emitter/detector on a slotted wheel). Requires a digital input and counts per revolution. Provides speed in Hz
Dependents: ES202FinalProject ES202_straight1 ES202_Final_Turn ES202_Turn ... more
Revision 0:c165325c9e3f, committed 2018-03-02
- Comitter:
- jdonnal
- Date:
- Fri Mar 02 16:52:58 2018 +0000
- Commit message:
- Initial Commit
Changed in this revision
Tach.cpp | Show annotated file Show diff for this revision Revisions of this file |
Tach.h | Show annotated file Show diff for this revision Revisions of this file |
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Tach.cpp Fri Mar 02 16:52:58 2018 +0000 @@ -0,0 +1,38 @@ + #include "Tach.h" + + //64 counts per rev + + Tach::Tach(PinName input, + int pulsesPerRev): input_(input){ + speed_ = 0.0; + pulsesPerRev_ = pulsesPerRev; + input_.mode(PullUp); + input_.rise(this, &Tach::update); + //input_.fall(this, &Tach::update); + timer_.start(); + for(int i=0;i<NSAMP;i++){ + speedBuffer_[i]=0.0; + } +} +int Tach::getCount(void){ + return count_; +} +float Tach::getSpeed(void) { + + float acc=0; + for(int i=0;i<NSAMP;i++){ + acc+=speedBuffer_[i]; + } + return acc/NSAMP; + +} + +void Tach::update(void) { + float speed; + static int i=0; + count_++; + speed = 1.0/(timer_.read()*pulsesPerRev_); + speedBuffer_[i%NSAMP]=speed; + i++; + timer_.reset(); +} \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Tach.h Fri Mar 02 16:52:58 2018 +0000 @@ -0,0 +1,75 @@ + +/* Single Channel Encoder as Speedometer + John Donnal 2018 +*/ + +#ifndef TACH_H +#define TACH_H + +/** + * Includes + */ +#include "mbed.h" + +/** + * Defines + */ +#define NSAMP 3 + +/** + * Tach Interface. + */ +class Tach { + +public: + + /** + * Constructor. + * + * Tracks rising and falling edges with interrupts, provides + * rotations per second (Hz) output + * + * @param input mbed pin for input channel. + * @param pulsesPerRev Number of pulses in one revolution. + * @param encoding The encoding to use. Uses X2 encoding by default. X2 + */ + Tach(PinName input, int pulsesPerRev); + + /** + * Read the state of the encoder. + * + * @return The current state of the encoder as a 2-bit number, where: + * bit 1 = The reading from channel B + * bit 2 = The reading from channel A + */ + float getSpeed(void); + int getCount(void); + +private: + + /** + * Update the pulse count. + * + * Called on every rising/falling edge of input + * + * update current speed estimate + */ + void update(void); + + /** + * Called on every rising edge of channel index to update revolution + * count by one. + */ + void index(void); + + InterruptIn input_; + Timer timer_; + + int pulsesPerRev_; + float speed_; + int count_; + int dt_; + float speedBuffer_[NSAMP]; +}; + +#endif /* TACH_H */