Signal frequency measurement problems

The official pyboard running MicroPython.
This is the reference design and main target board for MicroPython.
You can buy one at the store.
Target audience: Users with a pyboard.
Post Reply
letouriste001
Posts: 3
Joined: Wed Jul 20, 2016 2:38 pm

Signal frequency measurement problems

Post by letouriste001 » Wed Aug 24, 2016 2:44 pm

Hi,

I use 'X2' pin for measure the frequency, I have a square signal input on the pin. The signal frequency is 1hz. I use a µs timer. I use ExtInt for detect a rising edge and count time between two rising edge.

Frequency = 1 / Period
Frequency in Hz
Period in second

Well, my period is in µs

So, Frequency = 1000000 / period

I have a problem, my counter detect 1200 µs between two rising edge and it normally should detect 1000000 µs

There is my code :

main.py

Code: Select all

import pyb
import test

blueled=pyb.LED(4)
blueled.on()

test.init()

while True:
    test.measure()
    pyb.delay(1000)

test.py

Code: Select all

import pyb

pinFreq = None
periodTimer = None
micros = None
freq = 0
counter = 0
def callback(line):
    
    global micros
    global freq
    global counter
    
    print("line =", line)
    counter = micros.counter()
    freq = 1000000 / counter

def init(timer_id = 2, data_pin = 'Y2'):
    
    global pinFreq
    global periodTimer
    global micros
    
    pinFreq = pyb.Pin(data_pin)
    pinFreq.init(pyb.Pin.IN, pyb.Pin.PULL_UP)
    periodTimer = timer_id
    micros = pyb.Timer(periodTimer, prescaler=83, period=0x3fffffff)  # 1MHz ~ 1uS
    pyb.ExtInt(pinFreq, pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_UP, callback('toto'))

def measure():
    
    global freq
    global counter
    print("counter : " + str(counter))
    print("freq : " + str(freq) + "Hz")

Thanks a lot.

User avatar
dhylands
Posts: 3821
Joined: Mon Jan 06, 2014 6:08 pm
Location: Peachland, BC, Canada
Contact:

Re: Signal frequency measurement problems

Post by dhylands » Wed Aug 24, 2016 7:10 pm

This line:

Code: Select all

pyb.ExtInt(pinFreq, pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_UP, callback('toto'))
calls the callback function and takes the return value of None and then passes None as the callback to pyb.ExtInt.

I think that you meant to use:

Code: Select all

pyb.ExtInt(pinFreq, pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_UP, callback)
I also don't see where you're recording 2 edges and taking the difference between them.

If you want really accurate measurements, I recommend using the Input Capture mode of the timer. Here's an example:
https://github.com/dhylands/upy-example ... ic_test.py

Post Reply