Guest User

Untitled

a guest
Jul 17th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. const int PinA = 14; // Used for generating interrupts using CLK signal
  2. const int PinB = 12; // Used for reading DT signal
  3. const int PinSW = 13; // Used for the push button switch
  4.  
  5.  
  6. int lCnt = 0; // Keep track of last rotary value
  7. volatile int vPos = 0; // Updated by the ISR (Interrupt Service Routine)
  8.  
  9. void isr_event () {
  10. static unsigned long lIsrTmr = 0; // Last Interrupt time
  11. unsigned long IsrTmr = millis(); // Interrupt time
  12.  
  13. // If interrupts come faster than 5ms, assume it's a bounce and ignore
  14. if (IsrTmr - lIsrTmr > 5) {
  15. if (digitalRead(PinB) == LOW)
  16. {
  17. vPos++ ; // Could be +5 or +10
  18. }
  19. else {
  20. vPos-- ; // Could be -5 or -10
  21. }
  22.  
  23. // Restrict value from 0 to +100
  24. vPos = min(10, max(0, vPos));
  25.  
  26. // Keep track of when we were here last (no more than every 5ms)
  27. lIsrTmr = IsrTmr;
  28. }
  29. }
  30.  
  31. void setup()
  32. {
  33. Serial.begin(9600);
  34.  
  35. // Rotary pulses are INPUTs
  36. pinMode(PinA, INPUT);
  37. pinMode(PinB, INPUT);
  38.  
  39. pinMode(PinSW, INPUT_PULLUP); // Switch is floating so use the in-built PULLUP so we don't need a resistor
  40.  
  41. attachInterrupt(digitalPinToInterrupt(PinA), isr_event, LOW); // Attach the routine to service the interrupts
  42.  
  43. Serial.println(F("Starting...")); // Ready to go!
  44. }
  45.  
  46. void loop()
  47. {
  48.  
  49. // Is someone pressing the rotary switch?
  50. if ((!digitalRead(PinSW))) {
  51. vPos = 0;
  52. while (!digitalRead(PinSW))
  53. delay(10);
  54. }
  55.  
  56. // If the current rotary switch position has changed then update everything
  57. if (vPos != lCnt) {
  58. // Write out to serial monitor the value and direction
  59. Serial.println(vPos);
  60. // Keep track of this new value
  61. lCnt = vPos ;
  62. }
  63. }
Add Comment
Please, Sign In to add comment