简体   繁体   English

如何在python脚本中获取方波的频率

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

I'm using the TSL235 ( http://www.ti.com/lit/ds/symlink/tsl235.pdf ) light-to-frequency converter and the Raspberry Pi.我正在使用 TSL235 ( http://www.ti.com/lit/ds/symlink/tsl235.pdf ) 光频转换器和 Raspberry Pi。 The output of the sensor is a square wave (50% duty cycle) with frequency directly proportional to light intensity.传感器的输出是一个方波(50% 占空比),其频率与光强度成正比。

So I need to know (in a python script) which frequency gets to the Input GPIO-Pin of the Raspberry Pi.所以我需要知道(在 python 脚本中)哪个频率到达 Raspberry Pi 的 Input GPIO-Pin。

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我只找到了一个教程( http://playground.arduino.cc/Main/TSL235R ),它显示了一个 C 代码,但我不懂 C ......我只使用 python

Reading a GPIO Input isn't that hard so far:到目前为止,读取 GPIO 输入并不难:

#!/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?但是如何?

Use the time module.使用时间模块。 It has a clock function that is sensitive to 1 microsecond (1 MHz).它具有对 1 微秒 (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.查看传感器的数据表,它最高只能达到 500 kHz,这应该是足够的分辨率,可以在高光强度下进行准确的频率测量。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM