jgustavoam wrote: ↑Thu May 02, 2024 10:34 am
Hi Tuku,
First define the frequency range you want to use in your project.
For example from 1 Hz to 100KHz. If it is for frequencies below 1 Hz, the sample time will have to be changed.
sample_time = 1000000; ( one million miliseconds)
1. The pulse counter uses the ESP32 pcnt.
Pcnt has the following parameters:
a. input port;
b. input channel;
c. control port;
d. count on Pulse raising;
e. count on Pulse falling;
f. counting only with Control - high level;
g. maximum count limit.
The high level of control port enable the counter to count the pulses that arrive at the input port.
Pulses are counted both as the pulse rising and falling, to improve the counting average.
The sampling time is defined by the high resolution esp-timer, and it is defined in 1 second, in the sample-time variable.
If the count is greater than 20000 pulses during the counting time, overflow occurs and for with each overflow that occurs
the multPulses variable is incremented. Then pulse counter is cleared and proceed to counting.
Unfortunately the Pulse Counter has only 16 bits that may be used.
When the sampling time ends, a routine is called and the value in the pulse counter is read and saved.
A flag is set on to indicating that the pulse reading has ended.
In the loop, when verifying if the flag is on indicates that the pulse reading has finished, the value is calculated by multiplying
the number of overflow by 20000 and adding to the number of remaining pulses and dividing by 2, because it counted 2 times.
You must use two counters. One to count the positive part of the pulse and one for the negative part.
void init_PCNT(void) // Initialize and run PCNT unit
{
pcnt_config_t pcnt_config = { }; // PCNT unit instance
pcnt_config.pulse_gpio_num = PCNT_INPUT_SIG_IO; // Pulse input GPIO 34 - Freq Meter Input
pcnt_config.ctrl_gpio_num = PCNT_INPUT_CTRL_IO; // Control signal input GPIO 35
pcnt_config.unit = PCNT_COUNT_UNIT; // Unidade de contagem PCNT - 0
pcnt_config.channel = PCNT_COUNT_CHANNEL; // PCNT unit number - 0
pcnt_config.counter_h_lim = PCNT_H_LIM_VAL; // Maximum counter value - 20000
pcnt_config.pos_mode = PCNT_COUNT_INC; // PCNT positive edge count mode - inc
pcnt_config.neg_mode = PCNT_COUNT_INC; // PCNT negative edge count mode - inc
pcnt_config.lctrl_mode = PCNT_MODE_DISABLE; // PCNT low control mode - disable
pcnt_config.hctrl_mode = PCNT_MODE_KEEP; // PCNT high control mode - won't change counter mode
pcnt_unit_config(&pcnt_config); // Initialize PCNT unit
pcnt_counter_pause(PCNT_COUNT_UNIT); // Pause PCNT unit
pcnt_counter_clear(PCNT_COUNT_UNIT); // Clear PCNT unit
pcnt_event_enable(PCNT_COUNT_UNIT, PCNT_EVT_H_LIM); // Enable event to watch - max count
pcnt_isr_register(pcnt_intr_handler, NULL, 0, NULL); // Setup Register ISR handler
pcnt_intr_enable(PCNT_COUNT_UNIT); // Enable interrupts for PCNT unit
pcnt_counter_resume(PCNT_COUNT_UNIT); // Resume PCNT unit - starts count
}
Good luck