1

尝试通过上升沿用 OrangePi Zero 测量频率。我正在使用这个库来访问 gpio: http: //opi-gpio.readthedocs.io/en/latest/index.html

这是我的代码(Python 3.5):

def meas_freq_cb(receiver):
    self.meas_list.append(time.perf_counter())

GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.IN)
GPIO.add_event_detect(12, GPIO.RISING, callback=meas_freq_cb)
time.sleep(1)
GPIO.remove_event_detect(12)

i = 0
while i < len(self.meas_list)-1:
    a = self.meas_list[i+1] - self.meas_list[i]
    a = (a - int(a)) * 10000
    # a = round(a)
    print(a)
    i = i + 1
    if i > 200:
        break

GPIO.cleanup()

频率:来自精密发电机的 100Hz 方波。

结果:

0.8033299945964245
0.41291000343335327
1.2274799973965855
1.1154000003443798
0.9166499967250274
1.909970005726791
1.1483199978101766
3.992020001533092
0.5579099979513558
1.763299997037393
0.8991600043373182
23.93046999713988
7.611549999637646
4.15909999901487
13.988540003992966
4.470759995456319
1.9358100053068483
...

结果非常非常奇怪。我不知道有什么问题。频率很低,系统处于空闲状态,很简单的问题,但它不起作用..请协助..谢谢!

PS对不起我的英语不好

4

1 回答 1

0

在您的代码中,问题是a = (a - int(a)) * 10000。在你的meas_list是两个上升沿T之间的时间/计数器滴答声,相当于一个周期。频率 f = 1 / T,a = (a - int(a)) * 10000废话,它必须是

while i < len(self.meas_list)-1:
    T = self.meas_list[i+1] - self.meas_list[i] # time T between two rising edges
    f = (1 / T) * k # by definition and k is a constant that transforms the counter ticks returned by time.perf_counter() to real-world frequency ( calibration )
    print(f) 
    ...

time.perf_counter返回计数器的绝对值。

来源:了解 time.perf_counter() 和 time.process_time()

这是 RPi 代码到 OrangePi 的翻译(如何在 python 脚本中获取方波的频率)代码测量 10000 个上升沿发生的时间(持续时间)并计算频率 = 10000 / 持续时间 但是time.time()不精确了对于严肃的应用:

import time

impulse_count = 0

def meas_freq_cb(receiver):
    global impulse_count
    impuls_count+=1



NUM_CYCLES = 10000
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.IN)


start = time.time()
for impulse_count in range(NUM_CYCLES):
    GPIO.add_event_detect(12, GPIO.RISING, callback=meas_freq_cb)
duration = time.time() - start      #seconds to run for loop
frequency = NUM_CYCLES / duration   #in Hz

print(frequency)

GPIO.remove_event_detect(12)

在函数中使用全局变量

于 2018-08-08T22:22:55.057 回答