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

微笑、不失礼 提交于 2019-12-13 13:32:11

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/23187035/how-to-get-the-frequency-of-a-square-wave-in-a-python-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!