使用 pygame 从 Controller 读取信息,但是当我添加 arduinoData.write(str.encode(ALL_DATA))
时,它会降低很多速度,我该怎么办?
该行几乎添加到底部。是线的放置吗?它确实有效,但发送更新的速度不如我不写入串行。
import sys
import serial
import pygame
import time
from pygame.locals import *
pygame.init()
A0_value = '0'
A1_value = '0'
A2_value = '0'
A3_value = '0'
A4_value = '0'
A5_value = '0'
A6_value = '0'
B2 = '0'
B3 = '0'
B4 = '0'
B5 = '0'
global axis_data
##
arduinoData = serial.Serial('COM8',9600)
##
def main():
global axis_data , button_data
screen = pygame.display.set_mode((500, 700))
pygame.display.set_caption("Joystick example")
clock = pygame.time.Clock()
joysticks = {}
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True # Flag that we are done so we exit this loop.
if event.type == pygame.JOYBUTTONDOWN:
print("Joystick button pressed.")
if event.button == 0:
joystick = joysticks[event.instance_id]
if joystick.rumble(0, 0.7, 500):
print(
"Rumble effect played on joystick {}".format(
event.instance_id
)
)
if event.type == pygame.JOYBUTTONUP:
print("Joystick button released.")
# Handle hotplugging
if event.type == pygame.JOYDEVICEADDED:
# This event will be generated when the program starts for every
# joystick, filling up the list without needing to create them manually.
joy = pygame.joystick.Joystick(event.device_index)
joysticks[joy.get_instance_id()] = joy
print("Joystick {} connencted".format(joy.get_instance_id()))
if event.type == pygame.JOYDEVICEREMOVED:
del joysticks[event.instance_id]
print("Joystick {} disconnected".format(event.instance_id))
for joystick in joysticks.values():
axes = joystick.get_numaxes()
#print("Number of axes: {}".format(axes))
axis_str = [''] * axes
button_data = ""
axis_data = ""
for i in range(axes):
axis = joystick.get_axis(i)
axis_int = int(axis*100)
axis_str[i] = str(axis_int)
axis_data = axis_str[i] + "," + axis_data
#print("Axis {} value: {}".format(i, axis))
#print(axis_data)
buttons = joystick.get_numbuttons()
#print("Number of buttons: {}".format(buttons))
button_str = ['0'] * buttons
for i in range(buttons):
button = joystick.get_button(i)
button_str[i] = str(button)
#print("Button {} value: {}".format(i, button))
button_data = button_str[i] + "," + button_data
#print(button_data)
ALL_DATA = axis_data + button_data
ALL_DATA = ALL_DATA[:-1] + "!"
print(ALL_DATA)
arduinoData.write(str.encode(ALL_DATA))
# pygame.display.update()
clock.tick(60)
if __name__ == "__main__":
main()
# If you forget this line, the program will 'hang'
# on exit if running from IDLE.
pygame.quit()
最佳答案
以 9600 波特写入串口真的很慢。引用 this answer在波特率发送时间上,发送每个字母的时间略多于 1 毫秒(大约)。请注意,在 60 FPS 下,每帧允许约 17 毫秒。代码将此数据作为字符串写入,因此每次循环可能需要相当多的毫秒数。
一个真正容易的胜利是简单地使用更快的波特率。您至少可以尝试 230400
以获得 24 倍的加速。
此外,我们几乎从不将实时数据作为字符串发送。您可以使用 Python struct module将所有各种操纵杆读数打包成二进制数据,这样会更加紧凑。特别是如果您将按钮状态视为单个位,并且不需要在操纵杆位置上使用高分辨率。
最后,您的代码可以使用线程来执行串行通信,并行写入主 PyGame 循环。这适用于“IO 绑定(bind)”操作。
关于python - 写入串口时速度大幅降低,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72636988/