Advertisement
TolentinoCotesta

Encoder

Jun 27th, 2017
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.17 KB | None | 0 0
  1. *
  2. Demonstrates use of rotary encoder for motor
  3. direction and distance.
  4. */
  5.  
  6. #define CHA 2
  7. #define CHB 3
  8. #define CW_LED 8
  9. #define CCW_LED 7
  10.  
  11. volatile int master_count = 0; // universal count
  12. volatile byte INTFLAG1 = 0; // interrupt status flag
  13. bool dir = false;   //false CW, true = CCW
  14.  
  15. void setup() {
  16.   pinMode(CHA, INPUT);
  17.   pinMode(CHB, INPUT);
  18.   pinMode(CW_LED, OUTPUT); // LED connected to pin to ground
  19.   pinMode(CCW_LED, OUTPUT); // LED connected to pin to ground
  20.  
  21.   Serial.begin(115200);
  22.   Serial.println(master_count);
  23.  
  24.   attachInterrupt(0, flag, RISING);  
  25.   // interrupt 0 digital pin 2 positive edge trigger
  26. }
  27.  
  28. void loop() {
  29.  
  30.   if (INTFLAG1)   {
  31.        Serial.println(master_count);
  32.        delay(500);
  33.      INTFLAG1 = 0; // clear flag
  34.   } // end if
  35.  
  36.  
  37. } // end loop
  38.  
  39.  
  40. void flag() {
  41.   INTFLAG1 = 1;
  42.   // add 1 to count for CW
  43.   if (digitalRead(CHA) && !digitalRead(CHB)) {
  44.     master_count++ ;
  45.     digitalWrite(CW_LED, HIGH);
  46.     digitalWrite(CCW_LED, LOW);
  47.   }
  48.   // subtract 1 from count for CCW
  49.   if (digitalRead(CHA) && digitalRead(CHB)) {
  50.     master_count-- ;
  51.     digitalWrite(CW_LED, LOW);
  52.     digitalWrite(CCW_LED, HIGH);
  53.   }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement