Skip to content

Instantly share code, notes, and snippets.

@praeclarum
Created April 16, 2021 18:07
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 praeclarum/550f9559a112355e49b88dabff86bdc3 to your computer and use it in GitHub Desktop.
Save praeclarum/550f9559a112355e49b88dabff86bdc3 to your computer and use it in GitHub Desktop.
Arduino code to get clean values from even the noisiest and silliest rotary encoder
// From https://www.best-microcontroller-projects.com/rotary-encoder.html
static uint8_t prevNextCode = 0;
static uint16_t store=0;
int8_t read_rotary() {
static int8_t rot_enc_table[] = {0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0};
prevNextCode <<= 2;
if (digitalRead(RIGHT_PIN)) prevNextCode |= 0x02;
if (digitalRead(LEFT_PIN)) prevNextCode |= 0x01;
prevNextCode &= 0x0f;
// If valid then store as 16 bit data.
if (rot_enc_table[prevNextCode] ) {
store <<= 4;
store |= prevNextCode;
//if (store==0xd42b) return 1;
//if (store==0xe817) return -1;
if ((store&0xff)==0x2b) return -1;
if ((store&0xff)==0x17) return 1;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment