Keine Beschreibung
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

encoder.c 2.0KB

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