首页 > 解决方案 > 为什么我的感知帽上会出现随机不必要的延迟?是我的代码有问题还是我的树莓派速度有问题?

问题描述

为什么我的感知帽上会出现随机不必要的延迟?是我的代码有问题还是我的树莓派速度有问题?

编码:

from sense_hat import SenseHat
import time
from random import randint
from time import sleep

sense = SenseHat()
sense.low_light = False
sense.clear()

white = (255,255,255)
black = (0,0,0)

x = 0
y = 0
xspeed = 0
yspeed = 0
        
while True:
    
    
    pitch = sense.get_orientation()['pitch']
    roll = sense.get_orientation()['roll']
    
    if 270 < pitch < 345 and x < 7:
        sense.set_pixel(x,y,black)
        x+=1
    if 45 < pitch < 90 and x > 0:
        sense.set_pixel(x,y,black)
        x-=1
    if 45 < roll < 90 and y < 7:
        sense.set_pixel(x,y,black)
        y+=1
    if 270 < roll < 345 and y > 0:
        sense.set_pixel(x,y,black)
        y-=1
        
    sense.set_pixel(x,y,white)
    
    if 300 < pitch < 350:
        delay = (pitch-300)/200
    elif 300 < roll < 350:
        delay = (roll-300)/200
    elif 15 < pitch < 45:
        delay = (pitch-310)/-200
    elif 15 < roll < 45:
        delay = (roll-310)/-200
    else:
        delay = 0
    time.sleep(delay)

当我通过 15-45 轴倾斜帽子时,它就会播放。当我注释掉该部分时,代码运行干净。我想知道代码是否存在问题,或者只是我的 pi 速度慢。

标签: pythonmathraspberry-pi

解决方案


time.sleep()阻塞进程直到它完成

相反,您可能会考虑获取当前时间并将其减去,以查看是否还需要做更多的工作

delay = 0.2  # 200ms, though this should be whatever you need
sensors_last_checked = 0  # start small!

while True:
    # logic that always happens
    ...
    if time.time() - sensors_last_checked > delay:
        # now re-check sensors or whatever shouldn't happen all the time
        # work with the results?
        # you might change the delay here based upon the results
        sensors_last_checked = time.time()  # update
    ...
    # logic that may use another check

推荐阅读