Encoder test(rotation sensor) for CORE-1000
Dependencies: mbed
main.cpp
- Committer:
- zoot661
- Date:
- 2012-12-31
- Revision:
- 0:75e3cf27c60b
- Child:
- 1:38643472f93f
File content as of revision 0:75e3cf27c60b:
#include "mbed.h" DigitalIn phaseA( p5 ); // phase a of the quadrature encoder DigitalIn phaseB( p6 ); // phase b of the quadrature encoder int encoderClickCount = 0; // hold the signed value corresponding to the number of clicks left or right since last sample int previousEncoderState = 0; // keep a record of the last actioned sample state of the Qb+Qa outputs for comparison on each interrupt void quadratureDecoder( void ) { int currentEncoderState = (phaseB.read() << 1) + phaseA.read(); // create a two bit value out of phaseB and phaseA if( currentEncoderState == previousEncoderState ) { return; } switch( previousEncoderState ) { case 0: if( currentEncoderState == 1 ) { encoderClickCount--; } else if( currentEncoderState == 2 ) { encoderClickCount++; } break; case 1: if( currentEncoderState == 3 ) { encoderClickCount--; } else if( currentEncoderState == 0 ) { encoderClickCount++; } break; case 2: if( currentEncoderState == 0 ) { encoderClickCount--; } else if( currentEncoderState == 3 ) { encoderClickCount++; } break; case 3: if( currentEncoderState == 2 ) { encoderClickCount--; } else if( currentEncoderState == 1 ) { encoderClickCount++; } break; default: break; } previousEncoderState = currentEncoderState; } // read the rotation accumulator, and once read, reset it to zero int getClicks( void ) { int res = encoderClickCount; // this allows the knob to be rotated "while im not looking at it' and still return the encoderClickCount = 0; // actual number of clicks that have been rotated since last time I was checking it. return res; } int main() { Serial pc( USBTX, USBRX ); Ticker sampleTicker; // create a timer to sample the encoder int currentClicks; phaseA.mode( PullUp ); // phaseA is set with a built in pull-up resistor phaseB.mode( PullUp ); // phaseB is set with a built in pull-up resistor sampleTicker.attach_us( &quadratureDecoder, 1000 ); // make the quadrature decoder function check the knob once every 1000us = 1ms pc.printf( "Encoder test started\r\n" ); while( 1 ) { currentClicks = getClicks(); if( currentClicks != 0 ) { pc.printf( "click count = %d,%d\r\n", currentClicks, previousEncoderState ); } wait_ms( 200 ); } }