Advertisement
yumli

Encoder Simples Aprovado 1

Feb 28th, 2015
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. #define encoder0PinA 2
  2. #define encoder0PinB 3
  3.  
  4. volatile int encoder0Pos = 0;
  5.  
  6. void setup() {
  7.  
  8.  
  9. pinMode(encoder0PinA, INPUT);
  10. digitalWrite(encoder0PinA, HIGH); // turn on pullup resistor
  11. pinMode(encoder0PinB, INPUT);
  12. digitalWrite(encoder0PinB, HIGH); // turn on pullup resistor
  13.  
  14. attachInterrupt(0, doEncoder_Expanded, CHANGE); // encoder pin on interrupt 0 - pin 2
  15. // attachInterrupt(1, doEncoder, CHANGE);
  16. Serial.begin (9600);
  17. Serial.println("start"); // a personal quirk
  18.  
  19. }
  20.  
  21. void loop(){
  22. // do some stuff here - the joy of interrupts is that they take care of themselves
  23. }
  24.  
  25. /*void doEncoder() {
  26. /* If pinA and pinB are both high or both low, it is spinning
  27. * forward. If they're different, it's going backward.
  28. *
  29. * For more information on speeding up this process, see
  30. * [Reference/PortManipulation], specifically the PIND register.
  31. */
  32. /* if (digitalRead(encoder0PinA) == digitalRead(encoder0PinB)) {
  33. encoder0Pos++;
  34. } else {
  35. encoder0Pos--;
  36. }
  37.  
  38. Serial.println (encoder0Pos, DEC);
  39. }
  40.  
  41.  
  42. /* See this expanded function to get a better understanding of the
  43. * meanings of the four possible (pinA, pinB) value pairs:
  44. */
  45. void doEncoder_Expanded(){
  46. if (digitalRead(encoder0PinA) == HIGH) { // found a low-to-high on channel A
  47. if (digitalRead(encoder0PinB) == LOW) { // check channel B to see which way
  48. // encoder is turning
  49. encoder0Pos = encoder0Pos - 1; // CCW
  50. }
  51. else {
  52. encoder0Pos = encoder0Pos + 1; // CW
  53. }
  54. }
  55. else // found a high-to-low on channel A
  56. {
  57. if (digitalRead(encoder0PinB) == LOW) { // check channel B to see which way
  58. // encoder is turning
  59. encoder0Pos = encoder0Pos + 1; // CW
  60. }
  61. else {
  62. encoder0Pos = encoder0Pos - 1; // CCW
  63. }
  64.  
  65. }
  66. Serial.println (encoder0Pos, DEC); // debug - remember to comment out
  67. // before final program run
  68. // you don't want serial slowing down your program if not needed
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement