QEIx4 Example

Dependencies:   QEIx4 mbed

main.cpp

Committer:
jocis
Date:
2014-10-01
Revision:
3:922c100de8cd
Parent:
2:7c787d83331e

File content as of revision 3:922c100de8cd:

#include "mbed.h"
#include "QEIx4.h"

DigitalOut LEDalive(LED1);
DigitalOut LEDzero(LED2);
DigitalOut LEDup(LED4);
DigitalOut LEDdown(LED3);

Timer t;   // timer for polling

// ports for nxp LPC 1768
QEIx4 qei1(p30, p29, p28, (QEIx4::EMODE)(QEIx4::IRQ | QEIx4::SPEED));   // QEI with index signal for zeroing
QEIx4 qei2(p21, p22, NC,  QEIx4::IRQ_NO_JAMMING);                       // QEI with AB signals only
QEIx4 qei3(p25, p24, NC,  QEIx4::POLLING);                              // QEI without interrups in polling mode

// The callback functions
void myCounterChangeCallback(int value)
{
    static int valueLast=-1;

    if ( value > valueLast ) {
        LEDup = !LEDup;
        LEDdown = 0;
    } else {
        LEDdown = !LEDdown;
        LEDup = 0;
    }
    valueLast = value;
}

void myIndexTriggerCallback(int value)
{
    qei1 = 0;   // reset counter
    LEDzero = 1;
}

int main()
{
    t.start();

    qei1.setIndexTrigger(true);     // set the flag to zero counter on next index signal rises
    qei1.setSpeedFactor(1.0f);      // factor to scale from Hz (edges pe second = 4 * CPS) to user units (1.0=Hz, 1/(4*CPR)=rps, 1/(60*4*CPR)=rpm, 360/(4*CPR)=°/s, ...)
    qei3.attachIndexTrigger(myIndexTriggerCallback);
    
    qei3.attachCounterChange(myCounterChangeCallback);

    while(1) {
        qei3.poll();   // poll manually without interrupt - sampling in this loop with about 2kHz

        if ( t.read_ms() > 250 ) { // every quater second (4 Hz)
            t.reset();
            t.start();
            LEDalive = !LEDalive;

            printf ( "\r\n%6d  %6d  %6d  %10.3f", (int)qei1, (int)qei2, (int)qei3, (float)qei1.getSpeed() );   // print counter values
        }

        wait_us(20);   // for about 50kHz polling
    }
}