SHARE
TWEET

XOR interrupt

a guest Oct 23rd, 2019 78 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const byte XORout_pin = 2;     // XOR output pin
  2. const byte chanA_pin = 4;      // XOR channel A pin
  3. const byte chanB_pin = 5;      // XOR channel B pin
  4.  
  5. int chanA, chanB, XOR;
  6.  
  7. long pos_counter = 0;          // position counter
  8.  
  9. short XORstate = 4;
  10. short XORstate_ = XORstate;    // buffer
  11.  
  12. boolean hasChanged = 0;        // checking for changes in the position counter
  13.  
  14. void setup() {
  15.   pinMode(XORout_pin, INPUT);
  16.   pinMode(chanA_pin, INPUT);
  17.   pinMode(chanB_pin, INPUT);
  18.  
  19.   attachInterrupt(digitalPinToInterrupt(XORout_pin), trigger, CHANGE);
  20.   Serial.begin(9600);
  21. }
  22.  
  23. void trigger() {
  24.   hasChanged = true;
  25. }
  26.  
  27. void loop() {
  28.   if(hasChanged) {
  29.     hasChanged = false;
  30.     XOR = digitalRead(XORout_pin);
  31.     chanA = digitalRead(chanA_pin);
  32.     chanB = digitalRead(chanB_pin);
  33.  
  34.     XORstate = (1 << 2) | ((chanA != 0) << 1) | (chanB != 0);
  35.  
  36.     if (XORstate_ == XORstate) {
  37.       Serial.println("XOR state is identical");
  38.     } else if ((~XORstate_ & 3) == (XORstate & 3)) {
  39.       Serial.println("XOR state is inverted");
  40.     } else if ((XORstate_ & 1) == ((XORstate & 2) >> 1)) {
  41.       pos_counter--;
  42.     } else {
  43.       pos_counter++;
  44.     }
  45.  
  46.     XORstate_ = XORstate;
  47.     Serial.println(pos_counter);
  48.   }
  49. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top