Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Dependencies: mbed
main.cpp
- Committer:
- odb
- Date:
- 2017-02-03
- Revision:
- 1:38643472f93f
- Parent:
- 0:75e3cf27c60b
File content as of revision 1:38643472f93f:
#include "mbed.h"
DigitalIn phaseA( PA_0 ); // phase a of the quadrature encoder
DigitalIn phaseB( PA_1 ); // phase b of the quadrature encoder
DigitalIn click( PA_4 );
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 );
}
if(!click)
{ printf (" clicked \r\n");
}
wait_ms( 200 );
}
}