Advertisement
DL5SMB

Untitled

Aug 23rd, 2019
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. int enc_read(void) {
  2.   int result = 0;
  3.   byte newState;
  4.   int enc_speed = 0;
  5.  
  6.   unsigned long start_at = millis();
  7.  
  8.   while (millis() - start_at < 50) { // check if the previous state was stable
  9.     newState = enc_state(); // Get current state  
  10.    
  11.     if (newState != enc_prev_state)
  12.       delayMicroseconds(1);
  13.    
  14.     if (enc_state() != newState || newState == enc_prev_state)
  15.       continue;
  16.     //these transitions point to the encoder being rotated anti-clockwise
  17.     if ((enc_prev_state == 0 && newState == 2) ||
  18.       (enc_prev_state == 2 && newState == 3) ||
  19.       (enc_prev_state == 3 && newState == 1) ||
  20.       (enc_prev_state == 1 && newState == 0)){
  21.         result--;
  22.       }
  23.     //these transitions point o the enccoder being rotated clockwise
  24.     if ((enc_prev_state == 0 && newState == 1) ||
  25.       (enc_prev_state == 1 && newState == 3) ||
  26.       (enc_prev_state == 3 && newState == 2) ||
  27.       (enc_prev_state == 2 && newState == 0)){
  28.         result++;
  29.       }
  30.     enc_prev_state = newState; // Record state for next pulse interpretation
  31.     enc_speed++;
  32.     delayMicroseconds(1);
  33.   }
  34.   return(result);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement