Komunikacja Arduino z aplikacją python
Po zainstalowaniu python na komputerze, utwórz nowy projekt w wybranym IDE. Przeczytaj: Instalacja środowiska Python
Dodaj bibliotekę pyserial za pomocą pip.
pip install pyserial
Wysyłanie danych z komputera do Arduino
// Arduino
const int ledPin = 13;
char inData;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}
void loop() {
if (Serial.available() > 0) {
inData = Serial.read();
if (inData == 'H') {
digitalWrite(ledPin, HIGH);
}
if (inData == 'L') {
digitalWrite(ledPin, LOW);
}
}
}
#Python
import serial
import time
ser = serial.Serial('com5', 9600) #podaj odpowiedni com
time.sleep(3)
def sendCommand(c):
ser.write(c.encode())
while(True):
my_command = input("0-off, 1-on: ")
# my_command = input("L-off, H-on: ")
sendCommand(my_command)
Program z interfejsem graficznym tkinter
#python tkinter
import serial
import time
import tkinter
def set_button1_state():
btn_state_label['text'] = "LED ON"
ser.write(bytes('H', 'UTF-8'))
def set_button2_state():
btn_state_label['text'] = "LED OFF"
ser.write(bytes('L', 'UTF-8'))
ser = serial.Serial('com3', 9600)
time.sleep(3)
root = tkinter.Tk()
root.geometry('300x300')
root.title("Python with Arduino")
label3 = tkinter.Label(text = 'LED Controll',font=("Courier", 12,'bold')).pack()
btn_state_label = tkinter.Label(text = "___")
btn_state_label.pack()
button1state = tkinter.Button(root,
text="ON",
command=set_button1_state,
height = 4,
fg = "black",
width = 8,
bd = 5,
background = "green"
)
button1state.pack(side='top', ipadx=10, padx=10, pady=15)
button2state = tkinter.Button(root,
text="OFF",
command=set_button2_state,
height = 4,
fg = "black",
width = 8,
bd = 5,
background='red'
)
button2state.pack(side='top', ipadx=10, padx=10, pady=15)
tkinter.mainloop()
Wysyłanie danych z Arduino do komputera
//Arduino
const int countDelay = 1000;
unsigned long previousMillis = 0;
int counter = 0;
void setup() {
Serial.begin(9600);
}
void countWithDelay() {
if (millis() - previousMillis >= countDelay) {
previousMillis = millis();
Serial.println(counter);
counter++;
}
}
void loop() {
countWithDelay();
}
#Python
import serial
import time
port = 'COM5'
baud_rate = 9600
try:
ser = serial.Serial(port, baud_rate, timeout=1)
time.sleep(2)
print("Connected to:", port)
while True:
if ser.in_waiting > 0:
line = ser.readline().decode('utf-8', errors='ignore').rstrip()
print("Received:", line)
except serial.SerialException as e:
print("Error:", e)
finally:
ser.close()
print("Serial connection closed")