Som*_*ent 2 python pygame pyserial
使用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()
Run Code Online (Sandbox Code Playgroud)
以 9600 波特率写入串行确实相当慢。参考这个关于波特率发送时间的答案,发送每个字母大约需要 1 毫秒多一点。请注意,在 60 FPS 下,每帧允许约 17 毫秒。该代码将此数据写入为字符串,因此每个循环可能需要相当多的毫秒。
一个真正简单的方法是使用更快的波特率。您至少可以尝试23040024 倍加速。
而且我们几乎从不以字符串形式发送实时数据。您可以使用 Python struct 模块将所有各种操纵杆读数打包为二进制数据,这会更加紧凑。特别是如果您将按钮状态视为单个位,并且不需要操纵杆位置的高分辨率。
最后,您的代码可以使用线程来执行串行通信,与主 PyGame 循环并行写入。这对于“IO Bound”操作非常有效。
| 归档时间: |
|
| 查看次数: |
371 次 |
| 最近记录: |