Skip to content

Instantly share code, notes, and snippets.

@carlcrott
Created October 30, 2012 23:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlcrott/3983909 to your computer and use it in GitHub Desktop.
Save carlcrott/3983909 to your computer and use it in GitHub Desktop.
Upload this onto an Uno to find out the top and bottom value of the encoder you're working with
/* Rotary encoder read example */
/* Verified as working on Arduino Uno */
// connect ENCA pin to Uno pin 8
#define ENC_A 8
// connect ENCA pin to Uno pin 9
#define ENC_B 9
#define ENC_PORT PINB
void setup()
{
/* Setup encoder pins as inputs */
pinMode(ENC_A, INPUT);
digitalWrite(ENC_A, HIGH);
pinMode(ENC_B, INPUT);
digitalWrite(ENC_B, HIGH);
Serial.begin (115200);
Serial.println("Start");
}
void loop()
{
static uint8_t counter = 0; //this variable will be changed by encoder input
int8_t tmpdata;
/**/
tmpdata = read_encoder();
if( tmpdata ) {
Serial.print("Counter value: ");
Serial.println(counter, DEC);
counter += tmpdata;
}
}
/* returns change in encoder state (-1,0,1) */
int8_t read_encoder()
{
static int8_t enc_states[] = {0,-1,1,0,1,0,0,-1,-1,0,0,1,0,1,-1,0};
static uint8_t old_AB = 0;
/**/
old_AB <<= 2; //remember previous state
old_AB |= ( ENC_PORT & 0x03 ); //add current state
return ( enc_states[( old_AB & 0x0f )]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment