83 pcnt_unit_config_t unit_config = {
84 .low_limit = INT16_MIN,
85 .high_limit = INT16_MAX,
86 .flags = {.accum_count =
true},
88 esp_err_t error = pcnt_new_unit(&unit_config, &this->
pcnt_unit);
89 if (error != ESP_OK) {
90 ESP_LOGE(TAG,
"Creating PCNT unit failed: %s", esp_err_to_name(error));
94 pcnt_chan_config_t chan_config = {
95 .edge_gpio_num =
static_cast<gpio_num_t
>(this->pin->
get_pin()),
96 .level_gpio_num = GPIO_NUM_NC,
99 if (error != ESP_OK) {
100 ESP_LOGE(TAG,
"Creating PCNT channel failed: %s", esp_err_to_name(error));
104 pcnt_channel_edge_action_t rising = PCNT_CHANNEL_EDGE_ACTION_HOLD;
105 pcnt_channel_edge_action_t falling = PCNT_CHANNEL_EDGE_ACTION_HOLD;
108 rising = PCNT_CHANNEL_EDGE_ACTION_HOLD;
111 rising = PCNT_CHANNEL_EDGE_ACTION_INCREASE;
114 rising = PCNT_CHANNEL_EDGE_ACTION_DECREASE;
119 falling = PCNT_CHANNEL_EDGE_ACTION_HOLD;
122 falling = PCNT_CHANNEL_EDGE_ACTION_INCREASE;
125 falling = PCNT_CHANNEL_EDGE_ACTION_DECREASE;
129 error = pcnt_channel_set_edge_action(this->
pcnt_channel, rising, falling);
130 if (error != ESP_OK) {
131 ESP_LOGE(TAG,
"Setting PCNT edge action failed: %s", esp_err_to_name(error));
136 uint32_t max_glitch_ns = PCNT_LL_MAX_GLITCH_WIDTH * 1000u / ((
uint32_t) esp_clk_apb_freq() / 1000000u);
137 pcnt_glitch_filter_config_t filter_config = {
138 .max_glitch_ns = std::min(this->
filter_us * 1000u, max_glitch_ns),
140 error = pcnt_unit_set_glitch_filter(this->
pcnt_unit, &filter_config);
141 if (error != ESP_OK) {
142 ESP_LOGE(TAG,
"Setting PCNT glitch filter failed: %s", esp_err_to_name(error));
147 error = pcnt_unit_add_watch_point(this->
pcnt_unit, INT16_MIN);
148 if (error != ESP_OK) {
149 ESP_LOGE(TAG,
"Adding PCNT low limit watch point failed: %s", esp_err_to_name(error));
152 error = pcnt_unit_add_watch_point(this->
pcnt_unit, INT16_MAX);
153 if (error != ESP_OK) {
154 ESP_LOGE(TAG,
"Adding PCNT high limit watch point failed: %s", esp_err_to_name(error));
158 error = pcnt_unit_enable(this->
pcnt_unit);
159 if (error != ESP_OK) {
160 ESP_LOGE(TAG,
"Enabling PCNT unit failed: %s", esp_err_to_name(error));
163 error = pcnt_unit_clear_count(this->
pcnt_unit);
164 if (error != ESP_OK) {
165 ESP_LOGE(TAG,
"Clearing PCNT unit failed: %s", esp_err_to_name(error));
168 error = pcnt_unit_start(this->
pcnt_unit);
169 if (error != ESP_OK) {
170 ESP_LOGE(TAG,
"Starting PCNT unit failed: %s", esp_err_to_name(error));