single_phase_encoder.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #include "single_phase_encoder.h"
  2. #define DBG_SECTION_NAME "single_phase_encoder"
  3. #define DBG_LEVEL DBG_LOG
  4. #include <rtdbg.h>
  5. struct single_phase_encoder
  6. {
  7. struct encoder enc;
  8. rt_base_t pin; /* interrupt pin */
  9. };
  10. static void encoder_isr(void *args)
  11. {
  12. rt_int32_t* pulse_count = (rt_int32_t*)args;
  13. (*pulse_count)++;
  14. // LOG_D("Count %d", *pulse_count);
  15. }
  16. static rt_err_t single_phase_encoder_enable(void *enc)
  17. {
  18. RT_ASSERT(enc != RT_NULL);
  19. single_phase_encoder_t enc_sub = (single_phase_encoder_t)enc;
  20. // Attach interrupts
  21. rt_pin_mode(enc_sub->pin, PIN_MODE_INPUT_PULLUP);
  22. rt_pin_attach_irq(enc_sub->pin, PIN_IRQ_MODE_FALLING, encoder_isr, &(enc_sub->enc.pulse_count));
  23. enc_sub->enc.last_time = rt_tick_get();
  24. return rt_pin_irq_enable(enc_sub->pin, PIN_IRQ_ENABLE);
  25. }
  26. static rt_err_t single_phase_encoder_disable(void *enc)
  27. {
  28. RT_ASSERT(enc != RT_NULL);
  29. single_phase_encoder_t enc_sub = (single_phase_encoder_t)enc;
  30. return rt_pin_irq_enable(enc_sub->pin, PIN_IRQ_DISABLE);;
  31. }
  32. static rt_err_t single_phase_encoder_destroy(void *enc)
  33. {
  34. RT_ASSERT(enc != RT_NULL);
  35. single_phase_encoder_disable(enc);
  36. single_phase_encoder_t enc_sub = (single_phase_encoder_t)enc;
  37. rt_pin_detach_irq(enc_sub->pin);
  38. rt_free(enc);
  39. return RT_EOK;
  40. }
  41. single_phase_encoder_t single_phase_encoder_create(rt_base_t pin,rt_uint16_t pulse_revol)
  42. {
  43. // Malloc memory and initialize pulse_count and pin
  44. single_phase_encoder_t new_encoder = (single_phase_encoder_t)encoder_create(sizeof(struct single_phase_encoder));
  45. if(new_encoder == RT_NULL)
  46. {
  47. return RT_NULL;
  48. }
  49. new_encoder->pin = pin;
  50. new_encoder->enc.pulse_revol = pulse_revol;
  51. new_encoder->enc.enable = single_phase_encoder_enable;
  52. new_encoder->enc.disable = single_phase_encoder_disable;
  53. new_encoder->enc.destroy = single_phase_encoder_destroy;
  54. return new_encoder;
  55. }