#include "lab.h"
#include "driver/pulse_cnt.h"
#include "esp_log.h"
// Count rising edges on A only. B is not used: this example measures magnitude, not direction.
void app_main(void) {
    pcnt_unit_config_t u= {
        .low_limit=-30000,
        .high_limit=30000,
        .flags.accum_count=true
    };
    pcnt_unit_handle_t unit;
    ESP_ERROR_CHECK(pcnt_new_unit(&u,&unit));
    pcnt_chan_config_t c= {
        .edge_gpio_num=6,
        .level_gpio_num=-1
    };
    pcnt_channel_handle_t channel;
    ESP_ERROR_CHECK(pcnt_new_channel(unit,&c,&channel));
    ESP_ERROR_CHECK(pcnt_channel_set_edge_action(channel,PCNT_CHANNEL_EDGE_ACTION_INCREASE,PCNT_CHANNEL_EDGE_ACTION_HOLD));
    ESP_ERROR_CHECK(pcnt_unit_add_watch_point(unit,30000));
    ESP_ERROR_CHECK(pcnt_unit_add_watch_point(unit,-30000));
    pcnt_glitch_filter_config_t f= {
        .max_glitch_ns=1000
    };
    ESP_ERROR_CHECK(pcnt_unit_set_glitch_filter(unit,&f));
    ESP_ERROR_CHECK(pcnt_unit_enable(unit));
    ESP_ERROR_CHECK(pcnt_unit_clear_count(unit));
    ESP_ERROR_CHECK(pcnt_unit_start(unit));
    int last=0;
    int64_t last_us=esp_timer_get_time();
    for(;; ) {
        vTaskDelay(pdMS_TO_TICKS(200));
        int count=0;
        ESP_ERROR_CHECK(pcnt_unit_get_count(unit,&count));
        int64_t t=esp_timer_get_time();
        float pps=(count-last)*1000000.0f/(t-last_us);
        ESP_LOGI("encoder","count=%d pulses_per_second=%.2f",count,(double)pps);
        last=count;
        last_us=t;
    }
}
