Rotary Encoder handling library for mbed

Dependents:   MIDI_CW Gemphet8

REnc.cpp

Committer:
ChuckTimber
Date:
2014-08-06
Revision:
3:9dfe441065e9
Parent:
2:46173a05338e
Child:
4:916992052518

File content as of revision 3:9dfe441065e9:

#include "REnc.h"
#include "mbed.h"

/** class to make sound with a buzzer, based on a PwmOut
 *   The class use a timeout to switch off the sound  - it is not blocking while making noise
 *
 * Example:
 * @code
 * // REnc sample
 * #include "mbed.h"
 * #include "REnc.h"
 * void proc_REnc_right(void);
 * void proc_REnc_left(void);
 * 
 * // void proc_REnc_right(void) { }
 * // void proc_REnc_left(void)  { }
 * 
 * REnc renc(dp1, dp2);
 * 
 * int main()
 * {
 * 
 *     // renc.setHandleRight(&proc_REnc_right);
 *     // renc.setHandleLeft(&proc_REnc_left);
 *  
 *     while(1) {
 *         if (renc.CMD == CLOCKWISE) {
 *             proc_REnc_right();
 *             renc.CMD = STOP;
 *         } else if (renc.CMD == COUNTERCLOCKWISE) {
 *             proc_REnc_left();
 *             renc.CMD = STOP;
 *         }
 *         if (renc.STABLE) {
 *             // do_something
 *         }
 *     }
 * }
 * @endcode
 */

using namespace mbed;

// private function
/** sample_encoder input and process
 *
 */
void REnc::sample_encoder(void)
{
    static unsigned char i;
    static unsigned int cnt;
    
    i = (i << 2) + ((~_pinb & 0x01)<< 1) + (~_pina & 0x1);
    i &= 0xf;
    
    switch (i) {
        case 0x7:
        case 0xe:
            CMD = CLOCKWISE;
            cnt = RENC_EXECUTION_DELAY;
            STABLE = 0;
            if (mRightCallback != NULL)  { mRightCallback();  CMD = STOP; }
            break;
        case 0xb:
        case 0xd:
            CMD = COUNTERCLOCKWISE;
            cnt = RENC_EXECUTION_DELAY;
            STABLE = 0;
            if (mLeftCallback != NULL)   { mLeftCallback();   CMD = STOP; } 
            break;
        default:
            CMD = STOP;
            if (cnt)
                cnt--;
            else
                STABLE = 1;
    }
}

void REnc::setHandleRight(void (*fptr)(void))  { mRightCallback = fptr; }
void REnc::setHandleLeft(void (*fptr)(void))   { mLeftCallback  = fptr; }

 // constructor
 /** Create an REnc object connected to DigitalIn pins
  *
  * @param pina - Digital Input to A-phase of the rotary encoder
  * @param pinb - Digital Input to B-phase of the rotary encoder   
  */
REnc::REnc(PinName pina, PinName pinb) : _pina(pina), _pinb(pinb)
{
    CMD = STOP;
    STABLE = 1;
    mRightCallback  = NULL;
    mLeftCallback   = NULL;
    _tick.attach(this, &REnc::sample_encoder, RENC_SAMPLING_PERIOD);
}