Frequency Measurement on an ESP32 in MicroPython #ESP32 #MicroPython #Python

Via the MicroPython forums, user Roberthh provides the code for reading the frequency of an external signal from a digital pin on an ESP32 based microcontroller board. The code (MicroPython specific):


from machine import Pin, time_pulse_us, disable_irq, enable_irq
import time

p = Pin(18, Pin.IN)

while True:

sum = 0
loops = 100
for _ in range(loops//2):
state= disable_irq()
time_pulse_us(p, 1, 1000000)
sum += time_pulse_us(p, 1, 1000000)
enable_irq(state)
state= disable_irq()
time_pulse_us(p, 0, 1000000)
sum += time_pulse_us(p, 0, 1000000)
enable_irq(state)
print(500000*loops/sum)
time.sleep(0.97)

Rather compact. Perhaps someone would like to convert this to CircuitPython?

Roberthh states the code works up to 30 KHz, then starts to degrade. I’d say 30 KHz is pretty good, thanks.

See the post here.