by
1,488 14
0
5
2,200
0
Top 1% !
Famous
Tagged
Specified
OpenSource
Popularity: 9947th place

Published on:

Languagec++
LicenseMIT_X11

Rotary Encoder State table

Read Rotary Encoder using state table instead of interrupt
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/1400010/Rotary-Encoder-State-table?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
/* Common 2 pins rotary encoder (ignore push button pin) Default pin output = (0,0) Read each pin and combine them into one value then use it to index the state table to advance to next state State sequence 00->01->11->10->00 return -1 Next state 0 1 3 2 0 00->10->11->01->00 return +1 0 2 3 1 0 */ const int ENC_A = 2; const int ENC_B = 3; // State table static uint8_t stb[][4] = { // 0 1 2 3 {8,2,1,8}, //0 start here v=0 {0,8,1,3}, //1 0*2(-3-1-0 -1 {0,8,2,4}, //2 0*1(-3-2-0 {8,5,1,3}, //3 0-2*3(-1-0 -1 {8,2,6,4}, //4 0-1*3(-2-0 {7,5,8,3}, //5 0-2-3*1(-0 -1 {9,8,6,4}, //6 0-1-3*2(-0 }; static int encRead( int pa, int pb) { int8_t cx = 0; // initial state 0 int errCnt = 0; while (errCnt < 1550) { uint8_t v = digitalRead(pa) | digitalRead(pb)<<1; if (v < 4) { uint8_t nx = stb[cx][v]; if (nx > 6) { if (nx == 8) errCnt++; else return (8 - (int)nx); } else { cx = nx; } } else { cx = 0; errCnt++; } } return 0; } void setup() { Serial.begin(9600); pinMode( ENC_A, INPUT_PULLUP); pinMode( ENC_B, INPUT_PULLUP); } const int MAX_VAL = 64*6 -1; int lastPos = 0; void loop() { unsigned long sampleTime = millis(); int rv = encRead(ENC_A,ENC_B); sampleTime = millis() - sampleTime; if (rv == 0) { delay(50); } else { lastPos += rv; if (sampleTime < 20) sampleTime = 20; // simulate acceleration lastPos += rv*int(9000.0/(sampleTime*sampleTime)); if (lastPos < 0) lastPos = 0; if (lastPos > MAX_VAL) lastPos = MAX_VAL; Serial.print(lastPos); Serial.print(" "); Serial.println(sampleTime); } }
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus