Reading Frequencies with Python

Active today
Viewed 28 times

hello ladies and gents.

your knowledge helped me a lot until now but now i have a question.

i want to read out the frequency of a 3.3V squarewave. (The unit i want to readout is a capacitive moisture sensor: SensorLink)

the frequency the sensor puts out is between 5 and 20kHz. First i thought this will be an easy task, but i was wrong.

my approach: i wanted wait for a falling edge, use the time.time() function and save that value. wait for another falling edge and also safe the new value. so i should have the cycle time in ms. i looped that and made a average value.

heres the code i came up with for testing:

    import time
import RPi.GPIO as GPIO

def countfreq():
    GPIO.setup(17, GPIO.IN)
    samples = 1000
    timetotal = 0

    for i in range(samples):
        GPIO.wait_for_edge(17, GPIO.FALLING)
        start = time.time()
        GPIO.wait_for_edge(17, GPIO.FALLING)
        stop = time.time()
        duration = stop - start
        timetotal = timetotal + duration

    timeavg = timetotal / samples
    freq = 1 / timeavg

for i in range(100):
    print(i, ":", countfreq())

the problems i have now are: 1.) the frequency is not near frequency i have measured, but this would be no problem since this is no absolute value…

2.) the values i get are not consistant. they are all over the place without changing something that would change the capacity of the sensor. (i can post the output later since im at work at the moment)

the strange thing is that some sample C code works fine.Link to C code

im not very good in C so i dont understand much of the code although i have tried to understand it for hours now. :/ the strange thing is that they have 250 lines of code wich seems a lot X)

i hope someone can hint me in the right direction so that i am able to get this going. it appears strange to me since the frequency is not that high and the signal is really nice (i have measured it with an oscilloscope.)

heres a video i made about soldering and measuring the sensor if this is helpfull. VideoLink

so thank you all in advance. best wishes hans

 New contributor
  • Hi @Hansom DIY, Welcome and nice to meet you. Ah, let me see.I think what you need is a simple pulse counter program. Counting a pulse is like using a GPIO pin in input mode to read a manual button switch and adding up the counts, so newbie friendly python is good enough to do the simple job. You might also like to try the python GPIO.zero module which is easy to use. You can find a simple demo program in GPIO.zero in the following thread: ihttps://www.raspberrypi.org/forums/viewtopic.php?t=214457. Happy python programming and cheers. – tlfong01 18 hours ago   
  • “Welcome and nice to meet you. Ah, let me see.” Semantic value=0 Annoyance value=1 – Milliways 16 hours ago
  • Hi @Hansom, good day and nice to see you again. I am terribly sorry to confess that I made a unforgivable typo error yesterday about the weblink on using GPIO.Zero to count pulses. The link should read like this: raspberrypi.org/forums/viewtopic.php?t=214457. May apologies for any confusion caused. Yours faithfully. – tlfong01 1 min ago   Edit   


The C code appears to be an example I wrote to show usage of my pigpio C library.

A program showing how to use the gpioSetAlertFunc function to set a callback for GPIO state changes. A frequency count is generated for each monitored GPIO (frequencies up to 500kHz with a sample rate of 1μs).

You might be able to use Python for your purposes if you are using the more powerful Pi3 or Pi4.

Have a look at Class to monitor a PWM signal and calculate the frequency, pulse width, and duty cycle.

  • hello joan. thank you very much for the fast answer. i think i have come across your site before but didnt see the library. thanks a lot for the link, ill test that today. i am using an RPi 3 so i hope this will work… – Hansom DIY 18 hours ago
  • hello Joan. I have tested the code from your read_PWM script but it has very strange values on its output.18181.81818181818 18181.81818181818 20000.0 18181.81818181818 i have no idea why the values are so strange but I guess ill have to find another way. :/ – Hansom DIY 17 hours ago
  • That just looks like a number formatting when printed problem. Can you show the full output for one line? – joan 17 hours ago
  • Looking again that is not the output of my script. I have no idea what you have changed. – joan 17 hours ago
  • hello joan. this is just the output of the frequency. i have edited your script that the other two values are not printed. – Hansom DIY 16 hours ago
  • I suggest you only print the integer part. Frequencies of 20kHz and 18.181kHz do not seem unreasonable. – joan 16 hours ago
  • hi joan. thanks again for the reply. the problem is that it hops from exactly 20kHz to 18.181kHz without any physical sensor… the c code i mentioned above has a very stable output but around half the value of your code. the c code is off about 100Hz wich is plenty accurate enough… i dont understand what i have done wrong with your code… – Hansom DIY 15 hours ago
  • If you haven’t got a physical sensor and your input is floating, you could be picking up almost any nonsense. Either try it with the sensor connected, or put a resistor to ground (10k would be ideal) when you should read 0V – Chris H 13 hours ago
  • That is probably down to the default pigpio sampling rate of 5µs. A gap of 50µs is 20kHz, the next larger gap of 55µs is 18.181kHz. Restart the pigpio daemon with a higher sampling rate (personally I would use 2µs rather than the highest 1µs). sudo pigpiod -s 2 see pigpiod – joan 13 hours ago

Categories: Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: