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.c 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * encoder.c
  3. *
  4. * Based on https://github.com/mathertel/RotaryEncoder/blob/master/src/RotaryEncoder.cpp
  5. *
  6. * Copyright (c) 2024 Thomas Buck (thomas@xythobuz.de)
  7. *
  8. * Copyright (c) by Matthias Hertel, http://www.mathertel.de
  9. * This work is licensed under a BSD 3-Clause style license
  10. * https://www.mathertel.de/License.aspx.
  11. */
  12. #include <stdio.h>
  13. #include "pico/stdlib.h"
  14. #include "encoder.h"
  15. #define LATCH0 0
  16. #define LATCH3 3
  17. #define FOUR3 1 // 4 steps, Latch at position 3 only (compatible to older versions)
  18. #define FOUR0 2 // 4 steps, Latch at position 0 (reverse wirings)
  19. #define TWO03 3 // 2 steps, Latch at position 0 and 3
  20. #define ENCODER_MODE TWO03
  21. static const uint gpio_num[2] = {
  22. 9, 10
  23. };
  24. static const int8_t KNOBDIR[] = {
  25. 0, -1, 1, 0,
  26. 1, 0, 0, -1,
  27. -1, 0, 0, 1,
  28. 0, 1, -1, 0
  29. };
  30. static int8_t oldState;
  31. static int32_t position;
  32. static int32_t positionExt;
  33. static int32_t positionExtPrev;
  34. void encoder_init(void) {
  35. for (uint i = 0; i < 2; i++) {
  36. gpio_init(gpio_num[i]);
  37. gpio_set_dir(gpio_num[i], GPIO_IN);
  38. gpio_pull_up(gpio_num[i]);
  39. }
  40. oldState = gpio_get(gpio_num[0]) | (gpio_get(gpio_num[1]) << 1);
  41. position = 0;
  42. positionExt = 0;
  43. positionExtPrev = 0;
  44. }
  45. int32_t encoder_pos(void)
  46. {
  47. return positionExt;
  48. }
  49. void encoder_run(void) {
  50. int8_t thisState = gpio_get(gpio_num[0]) | (gpio_get(gpio_num[1]) << 1);
  51. if (oldState != thisState) {
  52. position += KNOBDIR[thisState | (oldState << 2)];
  53. oldState = thisState;
  54. switch (ENCODER_MODE) {
  55. case FOUR3:
  56. if (thisState == LATCH3) {
  57. // The hardware has 4 steps with a latch on the input state 3
  58. positionExt = position >> 2;
  59. }
  60. break;
  61. case FOUR0:
  62. if (thisState == LATCH0) {
  63. // The hardware has 4 steps with a latch on the input state 0
  64. positionExt = position >> 2;
  65. }
  66. break;
  67. case TWO03:
  68. if ((thisState == LATCH0) || (thisState == LATCH3)) {
  69. // The hardware has 2 steps with a latch on the input state 0 and 3
  70. positionExt = position >> 1;
  71. }
  72. break;
  73. }
  74. }
  75. }