我有几个 GPIO 端口都为低电平,并且想测量每个端口变为高电平所需的时间。我有一段工作代码可以提供可靠的读数,但只是看着它就让我觉得“必须有一种更有效的方法”。
代码在整个过程中应该保持不变,这样清除端口的数量就不会影响开销时间。(它应该尽可能恒定。)
这种排除使用以下方法的可能性,我都尝试过:
使用 GPIO.RISING 事件。使用线程处理端口更改。两者都会导致较差的结果,因为它涉及更多的代码和变量来处理状态更改时间,并将结果从事件处理程序/线程传递回主代码。
我意识到这本身并不是获得绝对准确测量的好方法,但结果已经足够好。(后台进程运行等影响 python 性能,举个例子。)我当然愿意接受更准确的解决方案,但是优化 python 代码将是一个很好的开始。
whileCount=0 # createvariables
highCounter=0
portsCleared=[]
results=[]
portStates=[]
for port in portList: #set GPIO ports to IN mode
GPIO.setup(port, GPIO.IN)
while (highCounter<portCount and whileCount < 1000): # loop until all ports are HIGH
whileCount += 1
portStates=[] # list in which the port states are stored
for port in portList: #get all port states
portStates.append(GPIO.input(port))
portCounter=0
for port in portList: #process all port states
portBoolean=portStates[portCounter]==GPIO.HIGH
if portBoolean and not port in portsCleared: #this specific port has gone to HIGH so its time is stored and it is added to the cleared list
portsCleared.append(port)
results[portCounter]=whileCount
highCounter+=1 #keep track of the amount of ports cleared, so the while loop can end once all ports are cleared
#print [portCounter,highCounter,portsCleared]
portCounter+=1
time.sleep(.001)
if whileCount==1000:#reached cap, set non cleared ports to cap
portCounter=0
for port in portList:
if not port in portsCleared:
results[portCounter]=1000
portCounter+=1
我希望在开销上浪费更少的时间,这样结果就会变得更准确一些。