|
| 1 | +#include "common-hal/countio/Counter.h" |
| 2 | + |
| 3 | +#include "py/runtime.h" |
| 4 | +#include "supervisor/shared/translate.h" |
| 5 | + |
| 6 | +#include "driver/pcnt.h" |
| 7 | + |
| 8 | +static void pcnt_init(countio_counter_obj_t* self) { |
| 9 | + int unit = PCNT_UNIT_0; |
| 10 | + // Prepare configuration for the PCNT unit |
| 11 | + pcnt_config_t pcnt_config = { |
| 12 | + // Set PCNT input signal and control GPIOs |
| 13 | + .pulse_gpio_num = self->pin->number, |
| 14 | + .ctrl_gpio_num = PCNT_PIN_NOT_USED, |
| 15 | + .channel = PCNT_CHANNEL_0, |
| 16 | + .unit = unit, |
| 17 | + // What to do on the positive / negative edge of pulse input? |
| 18 | + .pos_mode = PCNT_COUNT_INC, // Count up on the positive edge |
| 19 | + .neg_mode = PCNT_COUNT_DIS, // Keep the counter value on the negative edge |
| 20 | + }; |
| 21 | + // Initialize PCNT unit |
| 22 | + pcnt_unit_config(&pcnt_config); |
| 23 | + |
| 24 | + // Configure and enable the input filter |
| 25 | + pcnt_set_filter_value(unit, 100); |
| 26 | + pcnt_filter_enable(unit); |
| 27 | + |
| 28 | + // Initialize PCNT's counter |
| 29 | + pcnt_counter_pause(unit); |
| 30 | + pcnt_counter_clear(unit); |
| 31 | + |
| 32 | + // Everything is set up, now go to counting |
| 33 | + pcnt_counter_resume(unit); |
| 34 | +} |
| 35 | + |
| 36 | +void common_hal_countio_counter_construct(countio_counter_obj_t* self, |
| 37 | + const mcu_pin_obj_t* pin) { |
| 38 | + claim_pin(pin); |
| 39 | + self->pin = pin; |
| 40 | + pcnt_init(self); |
| 41 | +} |
| 42 | + |
| 43 | +bool common_hal_countio_counter_deinited(countio_counter_obj_t* self) { |
| 44 | + return self->pin == NULL; |
| 45 | +} |
| 46 | + |
| 47 | +void common_hal_countio_counter_deinit(countio_counter_obj_t* self) { |
| 48 | + if (common_hal_countio_counter_deinited(self)) { |
| 49 | + return; |
| 50 | + } |
| 51 | + reset_pin_number(self->pin->number); |
| 52 | + self->pin = NULL; |
| 53 | +} |
| 54 | + |
| 55 | +mp_int_t common_hal_countio_counter_get_count(countio_counter_obj_t* self) { |
| 56 | + int16_t count; |
| 57 | + pcnt_get_counter_value(PCNT_UNIT_0, &count); |
| 58 | + return count+self->count; |
| 59 | +} |
| 60 | + |
| 61 | +void common_hal_countio_counter_set_count(countio_counter_obj_t* self, |
| 62 | + mp_int_t new_count) { |
| 63 | + self->count = new_count; |
| 64 | + pcnt_counter_clear(PCNT_UNIT_0); |
| 65 | +} |
| 66 | + |
| 67 | +void common_hal_countio_counter_reset(countio_counter_obj_t* self) { |
| 68 | + common_hal_countio_counter_set_count(self, 0); |
| 69 | +} |
0 commit comments