Download the file
  1. #ifndef ROTARY_H
  2. #define ROTARY_H
  3.  
  4. #include "rotary_handler.h"
  5. #include "tasks.h"
  6. #include "hsphoto.h"
  7.  
  8. #ifndef ENCODER_PINA
  9. #error "ENCODER_PINA is not defined"
  10. #endif
  11.  
  12. #ifndef ENCODER_PINB
  13. #error "ENCODER_PINB is not defined"
  14. #endif
  15.  
  16. #if ENCODER_PINA >= ENCODER_PINB
  17. #error "Encoder pin A must be before pin B"
  18. #endif
  19.  
  20. #define BETWEEN(a, x , b) (a <= x && x <= b)
  21.  
  22. #if BETWEEN(0, ENCODER_PINA, 7) && BETWEEN(0, ENCODER_PINB, 7)
  23. #define ENC_PORT PIND
  24. #define ENC_BITS ((_BV(ENCODER_PINA)) | (_BV(ENCODER_PINB)))
  25. #define ENC_OFFS ENCODER_PINA
  26. #elif BETWEEN(8, ENCODER_PINA, 13) && BETWEEN(8, ENCODER_PINB, 13)
  27. #define ENC_PORT PINB
  28. #define ENC_BITS ((_BV(ENCODER_PINA-8)) | (_BV(ENCODER_PINB-8)))
  29. #define ENC_OFFS (ENCODER_PINA-8)
  30. #elif BETWEEN(14, ENCODER_PINA, 19) && BETWEEN(14, ENCODER_PINB, 19)
  31. #define ENC_PORT PINC
  32. #define ENC_BITS ((_BV(ENCODER_PINA-14)) | (_BV(ENCODER_PINB-14)))
  33. #define ENC_OFFS (ENCODER_PINA-14)
  34. #else
  35. #error "Encoder pin A and B are on different ATmega ports"
  36. #endif
  37.  
  38. class RotaryEncoder: public PeriodicTask {
  39. public:
  40. RotaryEncoder(RotaryEncoderHandler * handler, uint8_t enc_pina, uint8_t enc_pinb, uint8_t but_pin):
  41. PeriodicTask(5),
  42. handler(handler),
  43. enc_pina(enc_pina),
  44. enc_pinb(enc_pinb),
  45. old_pins(0),
  46. old_dir(0),
  47. dir(0),
  48. but_pin(but_pin),
  49. old_state(0) {
  50. pinMode(enc_pina, INPUT);
  51. pinMode(enc_pinb, INPUT);
  52. digitalWrite(enc_pina, HIGH);
  53. digitalWrite(enc_pinb, HIGH);
  54. pinMode(but_pin, INPUT);
  55. digitalWrite(but_pin, HIGH);
  56. }
  57. void do_run();
  58.  
  59. private:
  60. uint8_t read_direction();
  61. uint8_t read_click();
  62.  
  63. RotaryEncoderHandler * handler;
  64. uint8_t enc_pina, enc_pinb, old_pins;
  65. int8_t old_dir, dir;
  66. uint8_t but_pin;
  67. uint8_t old_state;
  68.  
  69. static int8_t enc_states[];
  70. static int8_t but_states[];
  71. };
  72.  
  73. #endif
  74. // vim:ft=arduino
  75.