I want to count pulses and find the frequency. Here is the picture of pulses from the oscilloscope:
Obviously, frequency is around 1/2.3 ms = 420 Hz.
First I tried this program:
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(26,GPIO.IN)
ecnt=0
def evnt(channel):
global ecnt
ecnt += 1
GPIO.add_event_detect(26, GPIO.RISING, callback=evnt)
while(True):
estr=ecnt
time.sleep(10)
efin=ecnt
print((efin-estr)/10)
Program returns frequencies around 1200 Hz!
I also tried this program:
import pigpio
import time
mypi=pigpio.pi()
mypi.set_mode(26, pigpio.INPUT)
wind_cb = mypi.callback(26)
while(True):
estr=wind_cb.tally()
time.sleep(10)
efin=wind_cb.tally()
print((efin-estr)/10)
This program returns frequency of 470 Hz, which is much better but still about 10% to much.
On suggestion from @joan I tried this
import pigpio
mypi=pigpio.pi()
mypi.set_mode(26, pigpio.INPUT)
ecnt=0
edat=[0,0]
def evnt(gpio,level,tick):
global ecnt
global edat
if level == 1:
ecnt += 1
edat=[ecnt,tick]
cb = mypi.callback(26,pigpio.RISING_EDGE,evnt)
while(True):
estr=edat
time.sleep(10)
efin=edat
tdif=pigpio.tickDiff(estr[1],efin[1])/1000000.0
if (tdif>0):
freq=(efin[0]-estr[0])/tdif
else:
freq=0
print(freq)
cb.cancel()
mypi.stop()
This makes minor improvement (time between two events is actually 10.03s and not 10s), so it still gives 10% higher frequency than it should.
What is wrong, what should I do?