Created
April 16, 2021 18:07
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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