Rotary Encoder handling library for mbed

Dependents:   MIDI_CW Gemphet8

REnc.cpp

Committer:
ChuckTimber
Date:
2014-08-12
Revision:
6:abd0d8d58fed
Parent:
5:3e6931797218

File content as of revision 6:abd0d8d58fed:

/**
 *  @file       REnc.cpp
 *  Project     Rotary Encoder handling Library
 *  @brief      Rotary Encoder handling library for mbed
 *  @version    1.0
 *  @author     Chuck Timber
 *  @date       12/08/2014
 */
#include "REnc.h"
#include "mbed.h"

/* class to handle a rotary encoder
 *
 */

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 (mCCCallback != NULL)  { mCCCallback();  CMD = STOP; }
            break;
        case 0xb:
        case 0xd:
            CMD = COUNTERCLOCKWISE;
            cnt = RENC_EXECUTION_DELAY;
            STABLE = 0;
            if (mCCWCallback != NULL)   { mCCWCallback();   CMD = STOP; } 
            break;
        default:
            CMD = STOP;
            if (cnt)
                cnt--;
            else
                STABLE = 1;
    }
}

/** set callback function to Clockwise TURN */
void REnc::setHandleCC(void (*fptr)(void))  { mCCCallback = fptr; }
/** set callback function to Counterclockwise TURN */
void REnc::setHandleCCW(void (*fptr)(void)) { mCCWCallback  = 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   
 *
 *  The pins are PullUp internally.
 */
REnc::REnc(PinName pina, PinName pinb) : _pina(pina), _pinb(pinb)
{
    _pina.mode(PullUp);
    _pinb.mode(PullUp);
    CMD = STOP;
    STABLE = 1;
    mCCCallback  = NULL;
    mCCWCallback   = NULL;
    _tick.attach(this, &REnc::sample_encoder, RENC_SAMPLING_PERIOD);
}