我尝试使用python和pyserial从串行监视器读取数据(我正在制作可以使用arduino游戏杆进行管理的游戏)。问题是我延迟读取x和y 3秒!是什么导致如此大的延迟,我该如何减少?
Arduino代码:
#define pinX A2
#define pinY A1
#define swPin 2
#define ledPin 13
void setup() {
Serial.begin(4800);
pinMode(ledPin, OUTPUT);
pinMode(pinX, INPUT);
pinMode(pinY, INPUT);
pinMode(swPin, INPUT);
digitalWrite(swPin, HIGH);
}
void loop() {
boolean ledState = digitalRead(swPin);
digitalWrite(ledPin, ledState);
int X = analogRead(pinX);
int Y = analogRead(pinY);
Serial.println(X);
Serial.println(Y);
}
Python代码:
import serial
from graphics import *
from pygame.locals import *
import time
import pygame
import math
ser=serial.Serial('COM5', baudrate=4800, timeout=10)
FPS = 10000000000
W = 1000
H = 500
WHITE = (255, 255, 255)
BLUE = (0, 70, 225)
dx = 0
dy = 0
V = 3
pygame.init()
sc = pygame.display.set_mode((W, H))
clock = pygame.time.Clock()
x = W // 2
y = H // 2
rotatex = 0
r = 50
running = True
while running:
ser.flush()
xr = int(ser.readline().decode('ascii').strip())
yr = int(ser.readline().decode('ascii').strip())
print(xr)
print(yr)
sc.fill(WHITE)
car = pygame.image.load('car.png')
track1 = pygame.image.load('track.png')
car_rect = car.get_rect(center=(x, y))
track1_rect = track1.get_rect(center=(500, 250))
car = pygame.transform.rotate(car, rotatex)
sc.blit(track1, track1_rect)
sc.blit(car, car_rect)
pygame.display.update()
if yr < 490:
if xr > 550:
rotatex += yr / 515 + 1
else:
rotatex -= yr / 515 + 1
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if yr > 550:
if xr > 550:
rotatex -= yr / 515 + 1
else:
rotatex += yr / 515 + 1
if rotatex >= 360:
rotatex = 0
if(rotatex < 0):
rotatex = 360 + rotatex
if xr < 490:
x = x + V * math.cos(math.radians(270-rotatex))
y = y + V * math.sin(math.radians(270-rotatex))
if xr > 550:
x = x - V * math.cos(math.radians(270-rotatex))
y = y - V * math.sin(math.radians(270-rotatex))
clock.tick(FPS)
pygame.event.pump()
pygame.display.quit()
pygame.quit()
sys.exit()
我尝试在serial.Serial
0中设置超时,但这给我一个错误:
xr = int(ser.readline()。decode('ascii')。strip())
ValueError:以10为底的int()无效文字:
因为它不能这么快地读取数据。