This week, I choose to use my microcontroller board, which I designed in Week 9's Output_Devices, for creating an interface application to turn LED on and off over serial communication on ESP32 using Tkinter in Python.
My objective is to establish a connection between the ESP32 and the created Tkinter Graphical User interfaces (Tk GUI) by programming it through Python. With the built-in circuit, communication between the ESP32 and LED is possible. Therefore, I will utilize the application's button to control the LED and toggle its state.
Serial Communication between a PC and an ESP32 is a simple and effective way to exchange data between the two devices. It can be used for a wide range of applications, such as controlling the ESP32 from a PC, or sending sensor data from the ESP32 to the PC for analysis.
Under here is the code I used to provide my interface to control the LED by turning it ON and/or OFF.
import serial
import tkinter as tk
serialPort = 'COM7' # change this to match your Arduino serial port
serialBaud = 9600
def sendChar(char):
ser = serial.Serial(serialPort, serialBaud)
ser.write(char.encode())
ser.close()
root = tk.Tk()
root.title("CONTROL LED WITH TKINTER UI AND ESP32")
buttonOn = tk.Button(root, text="TURN ON LED", command=lambda: sendChar('H'))
buttonOn.pack()
buttonOff = tk.Button(root, text="TURN OFF LED", command=lambda: sendChar('L'))
buttonOff.pack()
root.mainloop()
const int LED = 2;
int incomingByte; // a variable to read incoming serial data into
void setup() {
// initialize serial communication:
Serial.begin(9600);
// initialize the LED pin as an output:
pinMode(LED , OUTPUT);
}
void loop() {
// see if there's incoming serial data:
if (Serial.available() > 0) {
// read the oldest byte in the serial buffer:
incomingByte = Serial.read();
// if it's a capital H (ASCII 72), turn on the LED:
if (incomingByte == 'H') {
digitalWrite(LED, HIGH);
Serial.println(" H received");
}
// if it's an L (ASCII 76) turn off the LED:
if (incomingByte == 'L') {
digitalWrite(LED, LOW);
Serial.println(" L received");
}
}
}
below is the hero shot
© 2023 | Eric NDAYISHIMIYE | All Rights Reserved