我正在使用phidget bridge 4输入读取称重传感器。我试图以1 Hz的频率获取数据,所以我在while循环中使用time.sleep(1)
来根据需要每秒读取一次数据。为确保我的频率为1 Hz,我正在打印actuel time - the time of the beginning of the script
时的值,每个循环似乎都超过了1000ms。
代码:
from Phidget22.Phidget import *
from Phidget22.Devices.VoltageRatioInput import *
import time
start_time = round(time.time()*1000)
A1 = -6.147057832630E-06
B1 = -0.000288253826519
def onVoltageRatioChange(self, voltageRatio):
Masse = (voltageRatio - (B1) ) / (A1)
self.masse = Masse
def runningChannel(channel, dataInterval):
voltageRatioInput = VoltageRatioInput()
voltageRatioInput.setChannel(channel)
voltageRatioInput.setOnVoltageRatioChangeHandler(onVoltageRatioChange)
voltageRatioInput.openWaitForAttachment(5000)
voltageRatioInput.close()
return voltageRatioInput.masse
if __name__ == '__main__':
while True:
print(str(round(time.time()*1000) - start_time) + " : " + str(runningChannel(1, 1000)))
time.sleep(1)
控制台:
0 : -0.6478727917378451
1353 : -0.7766034823455521
2530 : -0.648175863557032
3914 : -0.7572446275502878
5089 : -0.6493878254748858
6474 : -0.6990053837124224
7650 : -0.6493878254748858
9033 : -0.8542015809786906
10209 : -0.6509030218913868
[您忘记了runningChannel()
调用也需要花费一些时间才能执行。要每秒执行某项操作(仍然近似),可以使用以下循环:
import time
while True:
start_time = time.time()
// your operations here
time.sleep(1 - (time.time() - start_time))
如果操作花费一秒钟以上,显然会失败
似乎您的函数可能需要一段时间才能返回(例如openWaitForAttachment(5000)
)将其添加到您故意添加的1秒延迟中,则延迟总是总是略大于1秒。如果要解决此问题,则必须跟踪时间(例如,您可以记录每次迭代开始时的时间,并且在逻辑运行之后仅等待剩余时间)