1
votes

I have set up communication between my laptop and Arduino using UART protocol. 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. I wanted to develop my existing code such that when the particular key i.e. 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.

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()
1

1 Answers

0
votes

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.

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.