Advertisement
Nanne118

Rotary Encoder ISR

Oct 12th, 2018
267
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.69 KB | None | 0 0
  1. /*
  2.  * Modified Rotary Encoder sketch
  3.  * Originally by Nick Gammon, as of 25th May 2011
  4.  * Modified by Nanne Kuperus, as of 09 October 2018
  5.  *
  6.  * TODO: Fix rotary encoder dual stepping (one turn increments / decrements count by two steps),
  7.  *          add reset button and add pretty RGB lighting on rotary encoder.
  8.  */
  9.  
  10. #define pinA 2
  11. #define pinB 3
  12. #define interrupt0 0 // that is pin D2
  13.  
  14. // #define arduinoPullups // Uncomment this to use Arduino (software) pullups, if you do not use hardware pullups.
  15.  
  16. volatile boolean fired; // Ensure that any variables for use inside the ISR are set as volatile, otherwise you cannot manipulate them.
  17. volatile boolean up;
  18.  
  19. int count;
  20.  
  21. void isr() // Interrupt Service Routine for a change to pinA on interrupt pin 0 (D2)
  22. {
  23.   if (digitalRead(pinA))
  24.   {
  25.     up = digitalRead(pinB);
  26.   }
  27.   else
  28.   {
  29.     up = !digitalRead(pinB);
  30.   }
  31.   fired = true;
  32. }
  33. // ISR END
  34.  
  35. void setup()
  36. {
  37.   Serial.begin(9600);
  38.  
  39.   #ifdef arduinoPullups
  40.   Serial.print("Arduino pullups will be enabled!");
  41.   digitalWrite(pinA, HIGH);
  42.   digitalWrite(pinB, HIGH);
  43.   #endif
  44.  
  45.   pinMode(pinA, INPUT);
  46.   pinMode(pinB, INPUT);
  47.  
  48.   attachInterrupt(interrupt0, isr, CHANGE); //interrupt0 is pin D2, interrupt 1 is pin D3  
  49. }
  50.  
  51. void loop()
  52. {
  53.   /*
  54.    * The original sketch used a static long to redefine int over and over again, I have instead defined it
  55.    * with the other variable definitions and as such it need not be a static variable (it can be).
  56.    */
  57.   // static long count = 0;
  58.  
  59.   if(fired)
  60.   {
  61.     if (up)
  62.     {
  63.       count++;
  64.     }
  65.     else
  66.     {
  67.       count--;
  68.     }
  69.     fired = false;
  70.     Serial.print("Count: ");
  71.     Serial.println(count);
  72.   }
  73.  
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement