No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

encoder.cpp 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #include <Arduino.h>
  2. #include <RotaryEncoder.h>
  3. #include "config.h"
  4. #include "config_pins.h"
  5. #include "debounce.h"
  6. #include "encoder.h"
  7. //#define DEBUG_ENCODER
  8. static Debouncer click(BTN_ENC);
  9. static int click_state = 0;
  10. static bool ignore_until_next_unclick = false;
  11. #ifdef KILL_PIN
  12. static Debouncer kill(KILL_PIN);
  13. static int kill_state = 0;
  14. #endif // KILL_PIN
  15. static RotaryEncoder encoder(BTN_EN1, BTN_EN2, RotaryEncoder::LatchMode::FOUR3);
  16. static int pos = 0;
  17. void encoder_init(void) {
  18. pinMode(BTN_ENC, INPUT_PULLUP);
  19. #ifdef KILL_PIN
  20. pinMode(KILL_PIN, INPUT_PULLUP);
  21. #endif // KILL_PIN
  22. }
  23. void encoder_run(void) {
  24. int cs = click.poll();
  25. if (ignore_until_next_unclick) {
  26. // dont set to 1 again until it was 0 once
  27. if (cs == 0) {
  28. ignore_until_next_unclick = false;
  29. }
  30. } else {
  31. click_state = cs;
  32. }
  33. #ifdef KILL_PIN
  34. kill_state = kill.poll();
  35. #endif // KILL_PIN
  36. encoder.tick();
  37. }
  38. int encoder_change(void) {
  39. int new_pos = encoder.getPosition();
  40. int diff = new_pos - pos;
  41. pos = new_pos;
  42. #ifdef DEBUG_ENCODER
  43. if (diff != 0) {
  44. Serial.print("encoder_change: ");
  45. Serial.print(diff);
  46. Serial.print(" ticks: ");
  47. Serial.println(new_pos);
  48. }
  49. #endif // DEBUG_ENCODER
  50. return diff;
  51. }
  52. int encoder_click(void) {
  53. int r = click_state;
  54. // only return 1 once for each click
  55. if (r == 1) {
  56. click_state = 0;
  57. ignore_until_next_unclick = true;
  58. #ifdef DEBUG_ENCODER
  59. Serial.println("encoder_click: 1");
  60. #endif // DEBUG_ENCODER
  61. }
  62. return r;
  63. }
  64. int kill_switch(void) {
  65. #ifdef KILL_PIN
  66. #ifdef DEBUG_ENCODER
  67. if (kill_state == 1) {
  68. Serial.println("kill_switch: 1");
  69. }
  70. #endif // DEBUG_ENCODER
  71. return kill_state;
  72. #else
  73. return 0;
  74. #endif // KILL_PIN
  75. }