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.

70 lines
2.3 KiB

  1. /*
  2. * Copyright 2018 Jack Humbert <jack.humb@gmail.com>
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation, either version 2 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. #include "encoder.h"
  18. #ifndef ENCODER_RESOLUTION
  19. #define ENCODER_RESOLUTION 4
  20. #endif
  21. #ifndef NUMBER_OF_ENCODERS
  22. #error "Number of encoders not defined by NUMBER_OF_ENCODERS"
  23. #endif
  24. #if !defined(ENCODERS_PAD_A) || !defined(ENCODERS_PAD_B)
  25. #error "No encoder pads defined by ENCODERS_PAD_A and ENCODERS_PAD_B"
  26. #endif
  27. static pin_t encoders_pad_a[NUMBER_OF_ENCODERS] = ENCODERS_PAD_A;
  28. static pin_t encoders_pad_b[NUMBER_OF_ENCODERS] = ENCODERS_PAD_B;
  29. static int8_t encoder_LUT[] = { 0, -1, 1, 0, 1, 0, 0, -1, -1, 0, 0, 1, 0, 1, -1, 0 };
  30. static uint8_t encoder_state[NUMBER_OF_ENCODERS] = {0};
  31. static int8_t encoder_value[NUMBER_OF_ENCODERS] = {0};
  32. __attribute__ ((weak))
  33. void encoder_update_user(int8_t index, bool clockwise) { }
  34. __attribute__ ((weak))
  35. void encoder_update_kb(int8_t index, bool clockwise) {
  36. encoder_update_user(index, clockwise);
  37. }
  38. void encoder_init(void) {
  39. for (int i = 0; i < NUMBER_OF_ENCODERS; i++) {
  40. setPinInputHigh(encoders_pad_a[i]);
  41. setPinInputHigh(encoders_pad_b[i]);
  42. encoder_state[i] = (readPin(encoders_pad_a[i]) << 0) | (readPin(encoders_pad_b[i]) << 1);
  43. }
  44. }
  45. void encoder_read(void) {
  46. for (int i = 0; i < NUMBER_OF_ENCODERS; i++) {
  47. encoder_state[i] <<= 2;
  48. encoder_state[i] |= (readPin(encoders_pad_a[i]) << 0) | (readPin(encoders_pad_b[i]) << 1);
  49. encoder_value[i] += encoder_LUT[encoder_state[i] & 0xF];
  50. if (encoder_value[i] >= ENCODER_RESOLUTION) {
  51. encoder_update_kb(i, COUNTRECLOCKWISE);
  52. }
  53. if (encoder_value[i] <= -ENCODER_RESOLUTION) { // direction is arbitrary here, but this clockwise
  54. encoder_update_kb(i, CLOCKWISE);
  55. }
  56. encoder_value[i] %= ENCODER_RESOLUTION;
  57. }
  58. }