Listiger_Lurch
Posts: 1
Joined: Sat Mar 12, 2016 6:54 pm

Measuring frequency via GPIO

Sat Mar 12, 2016 7:00 pm

Hi there,

I want to measure a fequency between 1 khz and about 20 khz.
Im using a raspberry pi 2 and an ATTEN function waveform generator.

The goal is to measure the frequency in the period of one second and print its value.

I created a program, that uses threading - it works quite god but there is one big problem.
the value is not stable enough for me. At 100hz I get readings from 99-101, at 1khz I get 950 to 1100.

Signal is: 50/50 duty square, amplitude is 3,3v.

My questions:

Are there any explicit designed GPIOs for this purpose?
Is there a problem with the code and is there a better solution for this?

The Code:

#!/usr/bin/env python
#coding: utf8

import threading
import time
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)

i = 0

def printit():
global i
print i
threading.Timer(1.0, printit).start()

i = 0

printit()

# continue with the rest of your code

# Ereignis Prozedur für Eingang HIGH
def doIfHigh(channel):
# Zugriff auf Variable i ermoeglichen
global i
# Wenn Eingang HIGH ist, Ausgabe im Terminal erzeugen
#print str(i)
# Schleifenzaehler erhoehen
i = i + 1

GPIO.add_event_detect(11, GPIO.RISING, callback = doIfHigh) # bouncetime = 1)

ghp
Posts: 1518
Joined: Wed Jun 12, 2013 12:41 pm
Location: Stuttgart Germany
Contact: Website

Re: Measuring frequency via GPIO

Sun Mar 13, 2016 3:39 pm

Hello,
the RPi environment with linux is not well suited to measure short times or event counts very precisely. For this reason, I prefer to have an atmel 328 controller in addition to RPi, dedicated to measure this sort of events. This adds some 5€ in hardware cost, but reduces software problems by days of headache.
See http://heppg.de/ikg/administration/pi/p ... 328_en.pdf for details.
Regards
Gerhard

When you post code, especially python, use the code-tag to preserver identation.

User avatar
joan
Posts: 14960
Joined: Thu Jul 05, 2012 5:09 pm
Location: UK

Re: Measuring frequency via GPIO

Sun Mar 13, 2016 4:35 pm

Last edited by joan on Mon Apr 08, 2019 7:23 am, edited 1 time in total.

tedder
Posts: 9
Joined: Sun Mar 18, 2018 3:28 am

Re: Measuring frequency via GPIO

Sun Apr 07, 2019 11:28 pm

joan wrote:
Sun Mar 13, 2016 4:35 pm
http://abyz.co.uk/rpi/pigpio/examples.h ... ead_PWM_py should do what you want.
For future finders of this forum, the above URL goes to a SEO site now. Here's the updated URL:
http://abyz.me.uk/rpi/pigpio/examples.h ... ead_PWM_py

Really it's just a link to a page with a downloadable zip that contains a single Python file. I found a copy of it on github too:
https://github.com/experiencor/self-dri ... ead_PWM.py

User avatar
joan
Posts: 14960
Joined: Thu Jul 05, 2012 5:09 pm
Location: UK

Re: Measuring frequency via GPIO

Mon Apr 08, 2019 7:24 am

@tedder

Thanks, I have now corrected the link.

Return to “Python”