pcnt_functions.c 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #include "freertos/FreeRTOS.h"
  2. #include "freertos/task.h"
  3. #include "freertos/queue.h"
  4. #include "driver/ledc.h"
  5. #include "driver/pcnt.h"
  6. #include "esp_attr.h"
  7. #include "esp_log.h"
  8. #include "config.h"
  9. #include "soc/dport_reg.h"
  10. // Example-code: https://github.com/espressif/esp-idf/blob/master/examples/peripherals/pcnt/pulse_count_event/main/pcnt_event_example_main.c
  11. // Counts full kWh
  12. static uint32_t kWh_Counter = 0;
  13. const int pcntUnit = PCNT_UNIT_0;
  14. float getkWh() {
  15. pcnt_intr_disable(pcntUnit);
  16. volatile int32_t count = DPORT_REG_READ(0x3FF57060);
  17. volatile uint32_t kWh = kWh_Counter;
  18. pcnt_intr_enable(pcntUnit);
  19. return (float)kWh + ((float)count/PULSES_PER_KWH);
  20. }
  21. static void IRAM_ATTR pcnt_example_intr_handler(void *arg)
  22. {
  23. kWh_Counter++;
  24. }
  25. void init_pcnt_unit()
  26. {
  27. /* Prepare configuration for the PCNT unit */
  28. pcnt_config_t pcnt_config = {
  29. // Set PCNT input signal and control GPIOs
  30. .pulse_gpio_num = PCNT_INPUT_SIG_IO,
  31. .ctrl_gpio_num = PCNT_INPUT_CTRL_IO,
  32. .channel = PCNT_CHANNEL_0,
  33. .unit = pcntUnit,
  34. // What to do on the positive / negative edge of pulse input?
  35. .pos_mode = PCNT_COUNT_INC, // Count up on the positive edge
  36. .neg_mode = PCNT_COUNT_DIS, // Keep the counter value on the negative edge
  37. // What to do when control input is low or high?
  38. .lctrl_mode = PCNT_MODE_REVERSE, // Reverse counting direction if low
  39. .hctrl_mode = PCNT_MODE_KEEP, // Keep the primary counter mode if high
  40. // Set the maximum and minimum limit values to watch
  41. .counter_h_lim = PULSES_PER_KWH,
  42. .counter_l_lim = 0,
  43. };
  44. /* Initialize PCNT unit */
  45. pcnt_unit_config(&pcnt_config);
  46. // How to read a periphial-register:
  47. //uint32_t c = p_pcnt_obj->hal.dev.hw.conf_unit[unit];
  48. //printf("Reg: %08x\n",(uint32_t)DPORT_REG_READ(0x3FF57000));
  49. /* Configure and enable the input filter */
  50. pcnt_set_filter_value(pcntUnit, 100);
  51. pcnt_filter_enable(pcntUnit);
  52. /* Enable int on high count limit */
  53. pcnt_event_enable(pcntUnit, PCNT_EVT_H_LIM);
  54. /* Initialize PCNT's counter */
  55. pcnt_counter_pause(pcntUnit);
  56. pcnt_counter_clear(pcntUnit);
  57. /* Install interrupt service and add isr callback handler */
  58. pcnt_isr_service_install(0);
  59. pcnt_isr_handler_add(pcntUnit, pcnt_example_intr_handler, (void *)pcntUnit);
  60. /* Everything is set up, now go to counting */
  61. pcnt_counter_resume(pcntUnit);
  62. }