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 2.0KB

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