Quadrature Encoder Interface for motion control with resistance to jitter and chatter on AB signals and motor vibrations

Dependents:   QEIx4_Example realtimeMM_V3 realtimeMM_V3

Quadrature Encoder Interface for Motion Control.

A class to decode pulses on a rotary encoder with AB signals (quadrature encoder). It uses all 4 edges of the AB signals to increase the counter resolution 4 times of cycles per rotation/revolution (CPR) (e.g. an encoder with 500 CPR get 2000 counts per rotation)

In opposite to most common QEI implementation this is resistant to jitter and chatter on AB signals and motor vibrations. When using interrupts (IRQ_NO_JAMMING-mode) only the needed edge and pin is activated to prevent jamming CPU time with unnecessary interrupts. Whes reaching the next position the edge that triggerd this position (state) is ignored to aboid oscillating up/down counts.

It can also be used in polling mode i.g. in idle routines if interrupts are not desired. At this mode be sure that the sampling frequency is heigher than the maximum rotation speed (expeced counts per second)

The internal state machine is based on a look up table (LUT) to minimize interrupt retention time and get all necessary flags at once.

Additional the rotation speed of the encoder can be measured. The algorithm is based on the measuring time between the edges to get a very precise speed at very slow rotation.

The library is designed to support closed loop speed- and motion-controller for also slow and smooth motions like movie camera motion control.

Quadrature Encoder Signals:

/media/uploads/jocis/qeix4.png

(+) Count UP; (-) Count DOWN

Revision:
1:ac6b7b1bf6c5
Parent:
0:46b8d5680f66
Child:
2:c0b87b11b9cd
--- a/QEIx4.h	Tue Sep 02 18:23:36 2014 +0000
+++ b/QEIx4.h	Tue Sep 30 12:34:07 2014 +0000
@@ -1,9 +1,10 @@
-/* 
+/*
 * @author Jochen Krapf
+* parts by Andy Kirkham
 *
 * @section LICENSE
 *
-* Copyright (c) 2012 Jochen Krapf, MIT License
+* Copyright (c) 2014 Jochen Krapf, MIT License
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
 * and associated documentation files (the "Software"), to deal in the Software without restriction,
@@ -21,7 +22,7 @@
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * @section DESCRIPTION
-* mbed QEI (quadrature encoder interface) library, for decoding AB signals from a rotary encoder 
+* mbed QEI (quadrature encoder interface) library, for decoding AB signals from a rotary encoder
 *
 * Use cases:
 * - Rotary encoder in closed loop motor regulation
@@ -30,13 +31,21 @@
 */
 
 #include "mbed.h"
-
+#include "FPointer_vi.h"
 
-/** Quadrature encoder interface. A class to decode pulses on a AB rotary encoder. It uses all 4 edges on AB signals to increase resolution 4 times.
+/** === Quadrature Encoder Interface. ===
+*
+* A class to decode pulses on a AB rotary encoder. It uses all 4 edges of the AB signals to increase resolution 4 times of cycles per rotation (CPR) (e.g. an encoder with 500 CPR get 2000 counts per rotation)
+*
+* In opposite to most common QEI implementation this is resistant to jitter on AB signals and motor vibration. When using interrupts only (IRQ_NO_JAMMING-mode) the needed edge and pin is activated to prevent jamming CPU time with unnecessary interrupts.
 *
-* In opposite to commen QEI implementation this is resistent to jitter on AB signals and motor vibration. When using interrupts only the needed edge and pin is activated to prevent jamming CPU time with interrups. 
+* It can also be used in polling mode i.g. in idle routines if interrupts are not desired.
+*
+* The internal state machine is based on a look up table (LUT) to minimize interrupt retention time and get all necessary flags at once.
 *
-* It can also be used in polling mode i.g. in idle routines.
+* Additional the rotation speed of the encoder can be measured. The algorithm is based on the measuring time between the edges to get a very precise speed at very slow rotation.
+*
+* The library is designed to support closed loop speed- and motion-controller for also slow and smooth motions like movie camera motion control.
 *
 * Example:
 *
@@ -50,43 +59,51 @@
 // ports for nxp LPC 1768
 QEIx4 qei1(p30, p29, p28);          // QEI with index signal for zeroing
 QEIx4 qei2(p27, p26, NC);           // QEI only with AB signals
-QEIx4 qei3(p25, p24, NC, false);    // QEI without interrups for polling mode
+QEIx4 qei3(p25, p24, NC, QEIx4::POLLING);    // QEI without interrups for polling mode
 
 int main() {
     t.start();
 
     qei1.SetZeroOnIndex(true);      // Set the flag to zero counter on next index signal rises
 
-    while(1) 
+    while(1)
     {
         qei3.poll();   // poll manually without interrupt - sampling in this loop with about 2kHz
-        
+
         if ( t.read_ms() > 500 )   // every half second
         {
             t.reset();
             t.start();
             myled = !myled;
-            
+
             printf ( "\r\n%6d %6d %6d", (int)qei1, (int)qei2, (int)qei3 );   // print counter values
         }
 
-    wait_us(500);   // for about 2kHz
+    wait_us(20);   // for about 50kHz
     }
 }
 * @endcode
 */
-class QEIx4 {
+class QEIx4
+{
 public:
 
+    typedef enum EMODE {
+        POLLING = 0,
+        IRQ = 1,
+        IRQ_NO_JAMMING = 2,
+        SPEED = 4,
+    } EMODE;
+
     /** constructor of QEIx4 object
     *
     * @param pinA     Pin number of input/interrupt pin for encoder line A. All port pins are possible except p19 and p20
     * @param pinB     Pin number of input/interrupt pin for encoder line B. All port pins are possible except p19 and p20
     * @param pinI     Pin number of input pin for optional encoder index or reference switch.
-    * @param bUseIRQ  Flag to use interrups to detect changes on line A and B. If FALSE the function poll() has to be called frequently
+    * @param eMode    Flag to use interrups to detect changes on line A and B. For none interrupt use mode POLLING and call the function poll() frequently. For optional speed calculation the mode SPEED can be ored
     */
-    QEIx4 ( PinName pinA, PinName pinB, PinName pinI=NC, bool bUseIRQ=true );
-    
+    QEIx4 ( PinName pinA, PinName pinB, PinName pinI=NC, EMODE eMode=IRQ );
+
     /** destructor of QEIx4 object
     */
     ~QEIx4();
@@ -95,57 +112,49 @@
     *
     * @return        Actual counter value
     */
-    int read()
-        { return _counter; }
+    int read() {
+        return _counter;
+    }
 
     /** Gets the actual counter value as int operator.
     *
     * @return        Actual counter value as int operator
     */
-    operator int ()     // int-Operator
-        { return _counter; }
-        
+    operator int () {   // int-Operator
+        return _counter;
+    }
+
     /** Sets the counter value at actual encoder position to given value.
     *
     * @param        Counter value
     */
-    void write ( int counter )
-        { _counter = counter; }
-        
+    void write ( int counter ) {
+        _counter = counter;
+    }
+
     /** Sets the counter value at actual encoder position to given value as assign operator.
     *
     * @param        Counter value
     */
-    int operator= ( int counter )     // Assign-Operator
-        { write(counter); return counter; }
-    
+    int operator= ( int counter ) {   // Assign-Operator
+        write(counter);
+        return counter;
+    }
+
     /** Polls the state machine manually and updates the counter value.
     */
-    void poll ()
-        { ProcessISR(); }
-    
-    /** Gets the actual counter value as float value. A value of 1.0 is one rotation
-    *
-    * @return        Actual encoder position as float
-    */
-    float GetPosition ()
-        { return (float)_counter / (_cpr*4.0); }
-        
-    /** Sets the number of cycles per rotation (CPR) for function GetPosition().
-    *
-    * @param        Cycles per rotation for a full rotation
-    */
-    void SetCPR ( int cpr )
-        { _cpr = cpr; }
-        
+    void poll () {
+        ProcessISR();
+    }
+
     /** Sets the flag for zeroing on next high on index pin while AB lines triggers next counting. The trigger forces the counter set to zero
     *
     * @param        Flag for triggering. Is reset on next zeroing
     */
-     void SetZeroOnIndex ( bool bZeroOnIndex )
-        { _bZeroOnIndex = bZeroOnIndex; }
+    void setZeroOnIndex ( bool bZeroOnIndex ) {
+        _bZeroOnIndex = bZeroOnIndex;
+    }
 
-        
     /** Callback in derived classes to act on counter change
     */
     virtual void CounterChange ( void ) {};
@@ -153,18 +162,126 @@
     /** Callback in derived classes to act on zeroing trigger
     */
     virtual void CounterZero ( void ) {};
-    
+
+    /** attach - Overloaded attachment function.
+    *
+    * Attach a C type function pointer as the callback.
+    *
+    * Note, the callback function prototype must be:-
+    * @code
+    * void myCallbackFunction(int);
+    * @endcode
+    * @param A C function pointer to call.
+    */
+    void attachCounterChange(void (*function)(int) = 0) {
+        fPointerCounterChange.attach (function);
+    }
+
+    /** attachCounterChange - Overloaded attachment function.
+     *
+     * Attach a C++ type object/method pointer as the callback.
+     *
+     * Note, the callback method prototype must be:-
+     * @code
+     *     public:
+     *         static void myCallbackFunction(int);
+     * @endcode
+     * @param A C++ object pointer.
+     * @param A C++ method within the object to call.
+     */
+    template<class T>
+    void attachCounterChange(T* item, void (T::*method)(int)) {
+        fPointerCounterChange.attach( item, method);
+    }
+
+    /** attachDirectionChange - Overloaded attachment function.
+    *
+    * Attach a C type function pointer as the callback.
+    *
+    * Note, the callback function prototype must be:-
+    * @code
+    * void myCallbackFunction(int);
+    * @endcode
+    * @param A C function pointer to call.
+    */
+    void attachDirectionChange(void (*function)(int) = 0) {
+        fPointerDirectionChange.attach (function);
+    }
+
+    /** attachDirectionChange - Overloaded attachment function.
+     *
+     * Attach a C++ type object/method pointer as the callback.
+     *
+     * Note, the callback method prototype must be:-
+     * @code
+     *     public:
+     *         static void myCallbackFunction(int);
+     * @endcode
+     * @param A C++ object pointer.
+     * @param A C++ method within the object to call.
+     */
+    template<class T>
+    void attachDirectionChange(T* item, void (T::*method)(int)) {
+        fPointerDirectionChange.attach( item, method);
+    }
+
+    /** Sets the factor for the getter-functions to convert in another unit (1.0=Hz, 1/(4*CPR)=rps, 1/(60*4*CPR)=rpm, 360/(4*CPR)=°/s, ...)
+    *
+    * @param fSpeedFactor - factor to scale from Hz (edges per second = 4 * CPS) to user units
+    */
+    void setSpeedFactor(float fSpeedFactor) {
+        _fSpeedFactor = fSpeedFactor;
+    }
+
+    /** Gets the actual speed as float value. The value is scales by the facor set by setPositionFactor()
+    *
+    * @return        Actual encoder speed as float
+    */
+    float getSpeed();
+
+    /** Sets the factor for the getter-functions to convert in another unit (e.g. CPR (cycles per rotation) * 4.0 to get 1.0 for a full rotation)
+    *
+    * @param fPositionFactor  Factor to scale from counts to user unit
+    */
+    void setPositionFactor ( float fPositionFactor ) {
+        _fPositionFactor = fPositionFactor;
+    }
+
+    /** Gets the actual counter value as float value. The value is scales by the facor set by setSpeedFactor()
+    *
+    * @return        Actual encoder position as float
+    */
+    float getPosition () {
+        return (float)_counter * _fPositionFactor;
+    }
+
+
 protected:
     InterruptIn _pinA, _pinB;
     DigitalIn _pinI;
+    FPointer_vi fPointerCounterChange;
+    FPointer_vi fPointerDirectionChange;
+
     int _counter;
-    short _mode;
-    int _cpr;
-    bool _bUseIRQ;
+    short _state;
+    short _eMode;
     bool _bZeroOnIndex;
-    
-    void ProcessISR ( void );
+
+    Timer _SpeedTimer;
+
+    unsigned int _nSpeedLastTimer;
+    unsigned int _nSpeedTimeoutMax;
+    unsigned int _nSpeedTimeoutCount;
+    int _nSpeedAvrTimeSum;
+    int _nSpeedAvrTimeCount;
+    float _fLastSpeed;
 
-private:    
-    static short _modeLUT[16];
+    void ProcessISR ( void );
+    void callback_timeout();
+
+    float _fPositionFactor;
+    float _fSpeedFactor;
+
+private:
+    static short _modeLUT[32];
 };
\ No newline at end of file