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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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 FOUR3
  21. static const uint gpio_num[2] = {
  22. 17, 18
  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. positionExt = -positionExt;
  60. }
  61. break;
  62. case FOUR0:
  63. if (thisState == LATCH0) {
  64. // The hardware has 4 steps with a latch on the input state 0
  65. positionExt = position >> 2;
  66. positionExt = -positionExt;
  67. }
  68. break;
  69. case TWO03:
  70. if ((thisState == LATCH0) || (thisState == LATCH3)) {
  71. // The hardware has 2 steps with a latch on the input state 0 and 3
  72. positionExt = position >> 1;
  73. positionExt = -positionExt;
  74. }
  75. break;
  76. }
  77. }
  78. }