I am working on my Visual Studio Code with Python.
The aim of the program is, by reading the keys pressed on the computer, send specific commands to an Arduino.
import serial
import time
from pynput import keyboard
import subprocess
# Configurar la conexión serial con Arduino
puerto_serial = serial.Serial('COM10', 9600) # Ajusta a tu puerto COM
time.sleep(2)
# Variable para controlar el Listener
finalizar = False # Para verificar si el programa debe finalizar
def on_press(key):
global finalizar # Indicamos que usaremos la variable global para finalizar
try:
if hasattr(key, 'char') and key.char is not None:
char = key.char
if char == 'q':
print("ending the program...")
finalizar = True # Establecemos la bandera para finalizar
return False # Detener el Listener
# Chequear si el carácter está en las velocidades permitidas
if char == 'z':
comando = f'v{12}n' # Comando de velocidad
puerto_serial.write(comando.encode()) # Enviar al Arduino
print(f"Velocidad configurada a {char} ")
# Comprobar la tecla presionada y enviar comandos a Arduino
if char == 'o':
print("Tecla 'o' para eyes")
puerto_serial.write(b'on') # Eyes
if char == 'u':
print("Flecha hacia arriba")
puerto_serial.write(b'un') # Comando hacia adelante
elif char == 'd':
print("Flecha hacia abajo")
puerto_serial.write(b'dn') # Comando hacia atrás
elif char == 'p':
print("Tecla p para parar")
puerto_serial.write(b'pn') # PARAR SILLA porque hay cambio
except Exception as e:
print(f"Error al procesar tecla: {e}")
# Iniciar el Listener para capturar eventos de teclado
with keyboard.Listener(on_press=on_press) as listener:
listener.join() # Mantener el listener en funcionamiento hasta que se presione 'q'
# Cerrar el puerto serial al finalizar
if puerto_serial.is_open:
puerto_serial.close()
print("Puerto serial cerrado.")
So what I want to do is, only in the section where the character ‘o’ is pressed, when ‘u’ or ‘d’ is pressed, the signal that must be sent to Arduino is a continuous pressed ‘u’ or ‘d’ key until ‘p’ is pressed.
So my question would be, how can I send a continuous key pressed signal to Arduino until a key triggers the order.
I have tried keyboard.press() and keyboard.release() but I do not know how to combine them with the puerto_serial.write()