這篇文章示範如何使用Python跟Arduino連結.並使用Python建立出來的圖形介面來控制
Arduino上LED 的ON/OFF.
底下是第一個範例的介紹連結:
http://arbu00.blogspot.tw/2016/07/pythonarduinoled.html
所建立出來的圖形介面如下圖所示,按下按鈕<Connect>去跟Arduino確認是否連線成功.
按下按鈕<ButtonA>則會傳送字元'a' 到arduino當指令去啟動LED跑馬燈1
按下按鈕<ButtonB>則會傳送字元'b' 到arduino當指令去啟動LED跑馬燈2
按下按鈕<ButtonC>則會傳送字元'c' 到arduino當指令去啟動LED閃燈的動作.
按下按鈕<Exit>則會傳送'ESC'鍵 字元到arduino當指令去結束視窗跟所有動作.
有關這個範例的實際示範及詳細的說明可以觀看底下的影片教學.
底下是本範例的Python &Arduino程式碼.
<Python source code>
# -*- coding:utf-8 -*-
from time import sleep
import serial
from msvcrt import getch
import tkinter
##==============================================================================
ser =serial.Serial("COM4", 115200, timeout=2) # Establish the connection on a specific port
##==============================================================================
##counter = 65 # "A"
##ser.write(chr(counter).encode('utf-8')) # Convert the decimal number to ASCII then send it to the Arduino
#cmd="Key in the Command".encode("utf-8")
#SerialWrite(cmd)
##======Write Serial Command to arduino============
def SerialWrite(command):
ser.write(command)
rv=ser.readline()
#print (rv) # Read the newest output from the Arduino
print (rv.decode("utf-8"))
sleep(1) # Delay for one tenth of a second
ser.flushInput()
##====================================
##===When button A be pressed then Send 'a' to arduino============
def SendCmdA():
Arduino_cmd='a'
cmd=Arduino_cmd.encode("utf-8")
SerialWrite(cmd)
#Show to LabelA----------------
LabelA.config(text="Send the command 'a' to Arduino")
LabelA.update_idletasks()
Tkwindow.update()
##===When button A be pressed then Send 'a' to arduino============
def SendCmdB():
Arduino_cmd='b'
cmd=Arduino_cmd.encode("utf-8")
SerialWrite(cmd)
#Show to LabelA----------------
LabelA.config(text="Send the command 'b' to Arduino")
LabelA.update_idletasks()
Tkwindow.update()
##====================================
##===When button A be pressed then Send 'a' to arduino============
def SendCmdC():
Arduino_cmd='c'
cmd=Arduino_cmd.encode("utf-8")
SerialWrite(cmd)
#Show to LabelA----------------
LabelA.config(text="Send the command 'c' to Arduino")
LabelA.update_idletasks()
Tkwindow.update()
##==Serial connect and Get arduino Ready================
def Serial_Connect():
print("Connecting to Arduino.....")
#Show to LabelA----------------
LabelA.config(text="Connecting to Arduino.....")
LabelA.update_idletasks()
Tkwindow.update()
sleep(1)
for i in range (1,10):
rv=ser.readline()
print("Loading...")
#Show to LabelA----------------
LabelA.config(text="Loading...")
LabelA.update_idletasks()
Tkwindow.update()
#----------------
#Debug print (rv) # Read the newest output from the Arduino
print (rv.decode("utf-8"))
ser.flushInput()
sleep(1) # Delay
Str_Message=rv.decode("utf-8")
#Debug print(Str[0:5])
if Str_Message[0:5]=="Ready":
print("Get Arduino Ready !")
#Show to LabelA----------------
LabelA.config(text="Get Arduino Ready !")
buttonStart.config(state="disabled")
LabelA.update_idletasks()
Tkwindow.update()
break
##==Serial connect Exit================
def All_Exit():
print("Exit.....")
#Show to LabelA----------------
LabelA.config(text="Exit.....")
LabelA.update_idletasks()
Tkwindow.update()
sleep(1)
chr_num = 27 ##ESC
cmd=(chr(chr_num).encode('utf-8'))
SerialWrite(cmd)
ser.close()
Tkwindow.destroy() # Kill the root window!
##------------------------------------------------------
Tkwindow=tkinter.Tk()
Tkwindow.title("Using Python to Control Arduino LED ON/OFF")
Tkwindow.minsize(600,400)
LabelA=tkinter.Label(Tkwindow,
bg='white',
fg='black',
text="Press 'connect' button to start",
width=30,
height=10,
justify=tkinter.LEFT
)
LabelA.pack(side=tkinter.TOP)
buttonA=tkinter.Button(Tkwindow,
anchor=tkinter.S,
text="Button A",
width=10,
height=1,
command=SendCmdA)
buttonA.pack(side=tkinter.LEFT)
buttonB=tkinter.Button(Tkwindow,
anchor=tkinter.S,
text="Button B",
width=10,
height=1,
command=SendCmdB)
buttonB.pack(side=tkinter.LEFT)
buttonC=tkinter.Button(Tkwindow,
anchor=tkinter.S,
text="Button C",
width=10,
height=1,
command=SendCmdC)
buttonC.pack(side=tkinter.LEFT)
buttonStart=tkinter.Button(Tkwindow,
anchor=tkinter.S,
text="Connect",
width=10,
height=1,
command=Serial_Connect)
buttonStart.pack(side=tkinter.RIGHT)
buttonEnd=tkinter.Button(Tkwindow,
anchor=tkinter.S,
text="Exit",
width=10,
height=1,
command=All_Exit)
buttonEnd.pack(side=tkinter.RIGHT)
Tkwindow.mainloop()
<Arduino source code>
//*****************************************************************************
//ArbuluckyChat V1.0
//阿布拉機的3D列印與機器人
//http://arbu00.blogspot.tw/
//
//2016/07/20 Writen By Ashing Tsai
//
//******************************************************************************
const int LedPin12=12;
const int LedPin11=11;
const int LedPin10=10;
String Str01="";
void setup() {
Serial.begin(115200); // set the baud rate
Serial.println("Ready"); // print "Ready" once
pinMode(LedPin12,OUTPUT);
pinMode(LedPin11,OUTPUT);
pinMode(LedPin10,OUTPUT);
digitalWrite(LedPin12,LOW);
digitalWrite(LedPin11,LOW);
digitalWrite(LedPin10,LOW);
}
void loop() {
if (Serial.available())
{
Str01="";
delay(1);
while(Serial.available())
{
Str01+=(char)Serial.read();
}
Serial.println(Str01); // send the data back in a new line so that it is not all one long line
}
if (Str01[0]=='a')
{
digitalWrite(LedPin12,HIGH);
digitalWrite(LedPin11,LOW);
digitalWrite(LedPin10,LOW);
delay(500);
digitalWrite(LedPin12,LOW);
digitalWrite(LedPin11,HIGH);
digitalWrite(LedPin10,LOW);
delay(500);
digitalWrite(LedPin12,LOW);
digitalWrite(LedPin11,LOW);
digitalWrite(LedPin10,HIGH);
delay(500);
}
if (Str01[0]=='b')
{
digitalWrite(LedPin12,HIGH);
digitalWrite(LedPin11,LOW);
digitalWrite(LedPin10,LOW);
delay(100);
digitalWrite(LedPin12,LOW);
digitalWrite(LedPin11,HIGH);
digitalWrite(LedPin10,LOW);
delay(100);
digitalWrite(LedPin12,LOW);
digitalWrite(LedPin11,LOW);
digitalWrite(LedPin10,HIGH);
delay(100);
}
if (Str01[0]=='c')
{
digitalWrite(LedPin12,HIGH);
digitalWrite(LedPin11,HIGH);
digitalWrite(LedPin10,HIGH);
delay(300);
digitalWrite(LedPin12,LOW);
digitalWrite(LedPin11,LOW);
digitalWrite(LedPin10,LOW);
delay(300);
}
}
加入阿布拉機的3D列印與機器人的FB粉絲團
https://www.facebook.com/arbu00/
Scan QRcode to join FB Fans.

