comparto el código en Arduino para la lectura de los dos botones usando los pines 2 y 3, y con un tiempo de retardo en la lectura de 100 ms. Son parámetros que se pueden modificar. De acuerdo al botón que se presione, se envía por el puerto serie una cadena para identificar cual botón se presionó.
const int buttonPin1 = 2;
const int buttonPin2 = 3;
int buttonState1 = 0;
int buttonState2 = 0;
void setup() {
Serial.begin(9600);
pinMode(buttonPin1, INPUT_PULLUP);
pinMode(buttonPin2, INPUT_PULLUP);
}
void loop() {
buttonState1 = digitalRead(buttonPin1);
buttonState2 = digitalRead(buttonPin2);
if (buttonState1 == LOW) {
Serial.println("boton1");
}
if (buttonState2 == LOW) {
Serial.println("boton2");
}
delay(100);
}
El código en Python modificado, contiene un hilo de ejecución para la lectura del puerto serie. Con la función invoke()
se presiona el botón.
import threading
import tkinter as tk
import serial
arduino = serial.Serial('COM3',9600)
leer = True
def funcion():
print("boton presionado")
def cerrar_ventana():
global leer
leer = False
ws.destroy()
def leer_arduino():
while leer:
if arduino.in_waiting > 0:
botonPresionado = arduino.readline().decode()[:-1].strip()
if botonPresionado == 'boton1':
boton.invoke()
elif botonPresionado == 'boton2':
boton2.invoke()
ws = tk.Tk()
ws.title("proyecto")
ws.geometry("300x350")
ws.config(bg = "grey")
ws.protocol("WM_DELETE_WINDOW", cerrar_ventana)
#--------------------------
mi_canvas = tk.Canvas(ws, height=300, width=300)
mi_canvas.pack()
#----------------
boton = tk.Button(ws, text = "Boton", height = 3, width = 14, bd = 4,command=funcion)
boton.place(x=0,y=300)
boton2 = tk.Button(ws, text = "Boton", height = 3, width = 14, bd = 4,command=funcion)
boton2.place(x=150,y=300)
#--------------------------
thread = threading.Thread(target=leer_arduino)
thread.start()
ws.mainloop()
Espero sea de ayuda.