How to get the frequency of a square wave in a python script

user3142695 picture user3142695 · Apr 20, 2014 · Viewed 11.5k times · Source

I'm using the TSL235 (http://www.ti.com/lit/ds/symlink/tsl235.pdf) light-to-frequency converter and the Raspberry Pi. The output of the sensor is a square wave (50% duty cycle) with frequency directly proportional to light intensity.

So I need to know (in a python script) which frequency gets to the Input GPIO-Pin of the Raspberry Pi.

I only found a tutorial (http://playground.arduino.cc/Main/TSL235R) which shows a C-code, but I do not understand C... I'm only working with python

Reading a GPIO Input isn't that hard so far:

#!/usr/bin/python
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setup(25, GPIO.IN)

impuls_count = 0
# Do next lines for i.e. 1000ms:
GPIO.wait_for_edge(25, GPIO.FALLING)
impuls_count = impuls_count + 1

I think I have to count the signals in a time intervall. But how?

Answer

mtadd picture mtadd · Apr 21, 2014

Use the time module. It has a clock function that is sensitive to 1 microsecond (1 MHz). Looking at your sensor's datasheet, it only goes up to 500 kHz, that should be sufficient resolution to get accurate frequency measurements at high light intensity.

Just calculate an average frequency of a set of input cycles.

import time

NUM_CYCLES = 10
start = time.time()
for impulse_count in range(NUM_CYCLES):
    GPIO.wait_for_edge(25, GPIO.FALLING)
duration = time.time() - start      #seconds to run for loop
frequency = NUM_CYCLES / duration   #in Hz