Advertisement
Guest User

ROTARY ENCODER W/ ATTINY85

a guest
Jan 8th, 2017
617
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.71 KB | None | 0 0
  1. #include "avr/interrupt.h";
  2. #include "avr/io.h";
  3.  
  4. #define enc0PinDT 3
  5. #define enc0PinCLK 4
  6. #define vol_up_pin 0
  7. #define vol_down_pin 1
  8.  
  9. volatile unsigned int tick = 0;
  10. volatile unsigned long tickTime = 0;
  11.  
  12. static boolean pins_on = false;
  13. static boolean rotating = false;
  14. static boolean lastTick = false;
  15.  
  16.  
  17. void setup()
  18. {
  19.   pinMode(enc0PinDT, INPUT);
  20.   pinMode(enc0PinCLK, INPUT);
  21.   pinMode(vol_up_pin, OUTPUT);
  22.   pinMode(vol_down_pin, OUTPUT);
  23.  
  24.   GIMSK = 0b00100000;       // Enable pin change interrupts
  25.   PCMSK = 0b00001000;       // Enable pin change interrupt for PB3 and PB4
  26.   sei();                    // Turn on interrupts
  27. }
  28. void vol(boolean a){
  29.   if (tick%7 == 0) {
  30.     if (a)
  31.       digitalWrite(vol_up_pin, HIGH);
  32.     else
  33.       digitalWrite(vol_down_pin, HIGH);
  34.     pins_on = true;
  35.   }
  36. }
  37. void loop()
  38. {
  39.   unsigned long cMillis = millis();
  40.   if (cMillis - tickTime > 1500 && tickTime != 0 && tick != 0) tick = 0;
  41.   /* /optional */
  42.   if (cMillis - tickTime > 5 && tickTime !=0 && pins_on) { // ontime interval for output pins are both 5ms
  43.     digitalWrite(vol_up_pin, LOW);
  44.     digitalWrite(vol_down_pin, LOW);
  45.     pins_on = false;
  46.   }
  47.   /* \optional */
  48.   while (rotating) {
  49.     delay(1); // debounce the signal by waiting 1 ms
  50.     tickTime = millis();
  51.    
  52.     int MSB = digitalRead(enc0PinDT); //most significant bit
  53.     int LSB = digitalRead(enc0PinCLK); //least significant bit
  54.    
  55.     if(MSB == LSB) { //CW
  56.       if (!lastTick) tick = 0;
  57.       tick++;
  58.       vol(true);
  59.       lastTick = 1;
  60.     } else { //CCW
  61.       if (lastTick) tick = 0;
  62.       tick++;
  63.       vol(false);
  64.       lastTick = 0;
  65.     }
  66.     rotating = false;
  67.   }
  68. }
  69. ISR(PCINT0_vect)
  70. {
  71.     rotating = true;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement