Advertisement
Guest User

Untitled

a guest
May 23rd, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. int pinA = 6; // Connected to CLK on KY-040
  2. int pinB = 8; // Connected to DT on KY-040
  3. int encoderPosCount = 0;
  4. int pinALast;
  5. int aVal;
  6. int pinBLast;
  7. int bVal;
  8. boolean bCW;
  9.  
  10. void setup() {
  11. pinMode (pinA,INPUT);
  12. pinMode (pinB,INPUT);
  13. /* Read Pin A
  14. Whatever state it's in will reflect the last position
  15. */
  16. pinALast = digitalRead(pinA);
  17. Serial.begin (9600);
  18. }
  19.  
  20. void loop() {
  21. aVal = digitalRead(pinA);
  22.  
  23. if (aVal != pinALast){ // Means the knob is rotating
  24. // if the knob is rotating, we need to determine direction
  25. // We do that by reading pin B.
  26. if (digitalRead(pinB) != aVal) { // Means pin A Changed first - We're Rotating Clockwise
  27. encoderPosCount ++;
  28. bCW = true;
  29. } else {// Otherwise B changed first and we're moving CCW
  30. bCW = false;
  31. encoderPosCount--;
  32. }
  33. Serial.print ("Rotated: ");
  34. if (bCW){
  35. Serial.println ("clockwise");
  36. }else{
  37. Serial.println("counterclockwise");
  38. }
  39. Serial.print("Encoder Position: ");
  40. Serial.println(encoderPosCount);
  41.  
  42. }
  43. pinALast = aVal;
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement