5

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.setmode(GPIO.BCM)
    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
    return(freq)


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

Hansom DIY
  • 59
  • 2

1 Answers1

1

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.

joan
  • 71,852
  • 5
  • 76
  • 108