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.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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(F("encoder_change: "));
  45. Serial.print(diff);
  46. Serial.print(F(" ticks: "));
  47. Serial.println(new_pos);
  48. }
  49. #endif // DEBUG_ENCODER
  50. return diff;
  51. }
  52. int encoder_rpm(void) {
  53. return encoder.getRPM();
  54. }
  55. int encoder_click(void) {
  56. int r = click_state;
  57. // only return 1 once for each click
  58. if (r == 1) {
  59. click_state = 0;
  60. ignore_until_next_unclick = true;
  61. #ifdef DEBUG_ENCODER
  62. Serial.println(F("encoder_click: 1"));
  63. #endif // DEBUG_ENCODER
  64. }
  65. return r;
  66. }
  67. int kill_switch(void) {
  68. #ifdef KILL_PIN
  69. #ifdef DEBUG_ENCODER
  70. if (kill_state == 1) {
  71. Serial.println(F("kill_switch: 1"));
  72. }
  73. #endif // DEBUG_ENCODER
  74. return kill_state;
  75. #else
  76. return 0;
  77. #endif // KILL_PIN
  78. }