Quadrature decoder

Dependents:   Telliskivi2_2014

qed.cpp

Committer:
Reiko
Date:
2013-08-31
Revision:
1:83b43784d90c
Parent:
0:0e8cb3139868
Child:
2:72d7f93f2881

File content as of revision 1:83b43784d90c:

#include "qed.h"

QED::QED(PinName channelA, PinName channelB)
    : interruptA(channelA), interruptB(channelB) {
 
    pulses = 0;
 
    //Workout what the current state is.
    int chanA = interruptA.read();
    int chanB = interruptB.read();
 
    //2-bit state.
    currState = (chanA << 1) | (chanB);
    prevState = currState;
 
    interruptA.rise(this, &QED::decode);
    interruptA.fall(this, &QED::decode);
    interruptB.rise(this, &QED::decode);
    interruptB.fall(this, &QED::decode); 
}

int QED::read() {
    int pulseCount = pulses;
    pulses = 0;
    return pulseCount;
}

void QED::decode() {
 
    int change = 0;
    int chanA  = interruptA.read();
    int chanB  = interruptB.read();
 
    currState = (chanA << 1) | (chanB);
 
    change = (prevState & PREV_MASK) ^ ((currState & CURR_MASK) >> 1);

    if (change == 0) {
        change = -1;
    }

    pulses -= change;
    
    prevState = currState; 
}