致力于为定制越野车创建数据采集系统。使用Raspberry Pi和自定义转速表(测试并确认工作)来测量RPM。在下面的代码中使用中断来获取RPM值。
def get_rpm():
GPIO.wait_for_edge(17, GPIO.FALLING)
start = time.time()
GPIO.wait_for_edge(17, GPIO.FALLING)
end = time.time()
duration = end - start
rpm = (1/duration)*60
return rpm此代码仅在引擎正在运行并产生火花时才起作用。如果没有火花,代码就会等待该边缘,不会继续执行。调用get_rpm()时,如果代码正在等待边缘,则会导致其他进程挂起。
我的解决方案是在另一个进程中获取引擎的状态。我认为它将在两个部分中工作得最好。
第1部分,在单独的线程中运行(循环):
GPIO.wait_for_edge(17, GPIO.RISING)
last = time.time第2部分,根据需要作为函数运行调用:
def get_state():
while time.time - last < .5:
engine_state = true
else:
engine_state = false
return engine_state随着第1部分将last保存到第2部分可访问的内存中,第2部分将根据火花塞最后一次触发的时间来确定汽车是否正在运行。使用engine_state作为比较器,只有当get_rpm()为真时,数据采集系统才会从engine_state获取并存储RPM值。
如何实现第1部分,以便可以在第2部分中使用last变量?last的变化将非常非常快。我不想在每次last更新时都将其存储到树莓派的SD卡上的文本文件中。我想在内存中存储last。
非常感谢!
发布于 2016-04-06 08:03:56
这只是为了获得灵感。我手头没有我的Pis,所以这篇文章是盲目地根据记忆写的。
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN)
# the line below is important. It'll fire on both rising and falling edges
# and it's non-blocking
GPIO.add_event_detect(17, GPIO.BOTH, callback=callback_func)
length_of_last_high = 0
length_of_last_low = 0
last_rise = 0
last_fall = 0
last_callback = 0
def callback_func(pin):
# all of these global variables aren't needed
# but I left them in for demo purposes
global last_rise
global last_fall
global last_callback
global length_of_last_high
global length_of_last_low
last_callback = time.time()
if GPIO.input(17):
print "Pin 17 is rising!"
length_of_last_high = last_callback - last_rise
last_rise = last_callback
else:
print "Pin 17 is falling!"
length_of_last_low = last_callback - last_fall
last_fall = last_callback
# last passed as parameter (the preferred solution if it works).
# You test it - I can't at the moment
def get_state(last=last_rise):
engine_state = False
if time.time() - last < .5:
engine_state = True
return engine_state
# last as global variable.
# This works too but global is bad practice if it can be avoided
# (namespace littering)
def get_state2():
global last_rise
engine_state = False
if time.time() - last_rise < .5:
engine_state = True
return engine_state
def main():
while True:
print "Not blocking! This loop could sleep forever. It wouldn't affect the readings"
time.sleep(1)
print get_state()
"""
GPIO.cleanup()
"""https://stackoverflow.com/questions/36438345
复制相似问题