尝试通过上升沿用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
...
结果非常非常奇怪。我不知道有什么问题。频率非常低,系统处于空闲状态,非常简单的问题,但是它不起作用。 请协助。。谢谢!
P.S。对不起,我的英语不好
答案 0 :(得分:0)
在您的代码中,问题是meas_list
。 a = (a - int(a)) * 10000
中的时间是两个上升沿 T 之间的时间/计数器滴答,相当于一个周期。频率f = 1 / T,所以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.time()
返回计数器的绝对值。
源:Understanding time.perf_counter() and time.process_time()
这是RPi代码到OrangePi(How to get the frequency of a square wave in a python script)的翻译,它测量10000个上升沿出现的时间(持续时间),并计算 frequency = 10000 /持续时间,但是{{ 1}}对于严重的应用程序来说太不精确了:
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)