[英]Controlling motor with pygame and pyserial
I have set up communication between my laptop and Arduino using UART protocol.我已经使用 UART 协议在我的笔记本电脑和 Arduino 之间建立了通信。 I have used pygame to take keyboard presses like
KEY_UP
, KEY_DOWN
and transmit a byte using pyserial from my laptop to the Arduino.我已经使用 pygame 来按下
KEY_UP
、 KEY_DOWN
之类的键盘按键,并使用 pyserial 从我的笔记本电脑向 Arduino 传输一个字节。 I wanted to develop my existing code such that when the particular key ie KEY_UP
is pressed the motor rotates which it does but as soon as I release the key it doesn't turn off maybe because the byte still remains at the serial buffer so basically I want the code to work such that as I release the key the motor should turn off.我想开发我现有的代码,这样当按下特定的键,即
KEY_UP
时,电机会旋转,但是一旦我释放键,它就不会关闭,可能是因为字节仍然保留在串行缓冲区中所以基本上我希望代码能够工作,这样当我松开钥匙时,电机应该会关闭。
import pygame
import serial
ser = serial.Serial('/dev/ttyACM1',9600)
pygame.init()
win = pygame.display.set_mode((100,100))
pygame.display.set_caption("ugv")
x = 20
y = 20
w = 30
h = 40
vel = 5
run = True
while run:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
ser.write(b'c')
if keys[pygame.K_RIGHT]:
ser.write(b'd')
if keys[pygame.K_UP]:
ser.write(b'a')
if keys[pygame.K_DOWN]:
ser.write(b'b')
pygame.draw.rect(win,(0,255,0),(x,y,w,h))
pygame.display.update()
pygame.quit()
You need add a case in your python code for when no key is pressed, and in this case send a signal telling the motor to stop.您需要在 python 代码中添加一个外壳,用于当没有按键被按下时,在这种情况下发送一个信号告诉电机停止。
Alternatively you can modify your Arduino code to only send motor signals for a small period of time after receiving a signal, and then resetting.或者,您可以修改您的 Arduino 代码,以便在收到信号后仅在一小段时间内发送电机信号,然后重置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.