如何在 while 循环内每 x 秒运行一次代码?
我的问题被简化了,我想根据数字 X 每 3 秒通过串口发送一个不同的信号到我连接的 Arduino 板,但是 X 的更新频率应该高于每三秒。 我可以每 3 秒只更新 while 循环内的特定部分,而其他所有内容都正常吗? 简而言之,这是我的 python 代码:
while something:
x= aChangingValue
if x > 130 and x < 300:
print('d')
arduino.write('d'.encode())
if x < 130:
print('r')
arduino.write('r'.encode())
if x > 300:
print('l')
arduino.write('l'.encode())
我尝试尝试系统时间和线程,但一无所获。有关相关主题的其他答案也对我不起作用。
My problem simplified is that I want to send a different signal depending on the number X through serial to my connected Arduino board every 3 seconds however X should be updated more often than every three seconds.
Can I only update a specific part inside the while loop every 3 seconds and everything else normally?
Here is my python code in a nutshell:
while something:
x= aChangingValue
if x > 130 and x < 300:
print('d')
arduino.write('d'.encode())
if x < 130:
print('r')
arduino.write('r'.encode())
if x > 300:
print('l')
arduino.write('l'.encode())
I tried experimenting with the system time and threads but got nowhere. Other answers on relating topics also didn't work for me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这将执行您所要求的操作。
但请记住,这会阻塞该睡眠间隔。您的程序中没有发生任何其他事情,这可能工作得很好,但根据其他情况的发生,可能不会像您想象的那样工作。
This will do what you've asked.
But remember that this is blocking for that sleep interval. Nothing else is happening in your program, which may work just fine, but depending on what else is happening, may not work how you imagine.