写入串口时,速度大大降低



使用pygame从控制器读取信息,但是当我添加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波特率写入串口确实很慢。在波特率发送时间上引用这个答案,发送每封信大约需要1毫秒多一点。请注意,在60 FPS下,每帧允许约17毫秒。代码将这些数据作为字符串写入,因此每次循环可能会花费相当多毫秒。

一个真正的简单的方法是使用更快的波特率。你至少可以试试230400的24倍加速。

同样,几乎从不以字符串的形式发送实时数据。您可以使用Python结构模块将所有不同的操纵杆读数打包成二进制数据,这将更加紧凑。特别是如果你将按键状态视为单个比特,并且不需要操纵杆位置的高分辨率。

最后,您的代码可以使用一个线程来执行串行通信,与主PyGame循环并行编写。这在"IO边界"上运行良好。操作。

最新更新