I am a bit new to python and I wanted to write a program to send data to an arduino whenever w, s, a or d was held down. Well I also decided to make it a bit more interactive so whenever I held down a key it also displayed it on the screen.The program runs fine but starts to lag after some time and I have been unable to fix it so some help will be much appreciated.
import pygameimport serial# Initialize Pygamepygame.init()clock = pygame.time.Clock()# Set up the serial connection to Arduinoarduino_port = "COM6" # Change this to your Arduino portbaud_rate = 9600try: ser = serial.Serial(arduino_port, baud_rate, timeout=1)except serial.SerialException as e: print(f"Error opening serial port: {e}") exit()# Set up Pygame windowwindow_size = (250, 250)screen = pygame.display.set_mode(window_size)pygame.display.set_caption("Indrajeet's Control")# Colorsblack = (0, 0, 0)white = (255, 255, 255)red = (255, 0, 0)green = (0, 255, 0)blue = (0, 0, 255)# Fontfont = pygame.font.Font(None, 36)# Function to send data to Arduinodef send_data(direction): ser.write(direction.encode())# Main looprunning = Truewhile running: # Limit frame rate clock.tick(30) # Cap frame rate to 30 frames per second for event in pygame.event.get(): if event.type == pygame.QUIT: running = False keys = pygame.key.get_pressed() # Indicators indicator_w = green if keys[pygame.K_w] else red indicator_a = green if keys[pygame.K_a] else red indicator_s = green if keys[pygame.K_s] else red indicator_d = green if keys[pygame.K_d] else red if keys[pygame.K_a] and keys[pygame.K_w]: send_data("a") elif keys[pygame.K_d] and keys[pygame.K_w]: send_data("d") elif keys[pygame.K_w]: send_data("w") elif keys[pygame.K_a] and keys[pygame.K_s]: send_data("<") elif keys[pygame.K_d] and keys[pygame.K_s]: send_data(">") elif keys[pygame.K_s]: send_data("s") else: send_data("0") # Clear the screen screen.fill(white) # Draw buttons with indicators button_size = (50, 50) button_spacing_x = 20 button_spacing_y = 30 pygame.draw.rect(screen, indicator_w, (100, 50, *button_size)) pygame.draw.rect(screen, indicator_a, (50, 100, *button_size)) pygame.draw.rect(screen, indicator_s, (100, 100, *button_size)) pygame.draw.rect(screen, indicator_d, (150, 100, *button_size)) # Display labels text_w = font.render("W", True, white) text_a = font.render("A", True, white) text_s = font.render("S", True, white) text_d = font.render("D", True, white) screen.blit(text_w, (115, 65)) screen.blit(text_a, (65, 115)) screen.blit(text_s, (115, 115)) screen.blit(text_d, (165, 115)) # Update the display pygame.display.flip() #pygame.event.pump()# Close the serial connectionser.close()# Quit Pygamepygame.quit()
I limited the frame-rate and it helped quite a bit by increasing the amount of time before the lag starts but it didn't solve the problem. I also tried adding pygame.event.pump()
but it also didn't seem to help.