這篇文章示範如何使用Python跟Arduino連結.並簡單的控制LED ON/OFF.
由於Python 是跨平台的程式語言所以可以安裝在一般電腦的windows上,也可以安裝在
使用Linux的系統如樹梅派.
底下的範例程式是在一般的電腦windows 裡執行Python程式.
使用這樣的連結的好處在於分工,例如我們可以把影像識別或是語音識別建立在執行速度比較快的CPU上,如一般PC或是樹梅派,而把一些如機械手臂的動作或是資料感測建立在arduino端,透過Python 的套件Pyserial 就可以從Python端下自訂的文字命令去控制Arduino ,或是得到從Arduino端回傳過來的一些感測器數值資料.
為什麼選擇Python?因為Python 語法簡單易學但是功能強大,並且世界上網路上都有開源的
原始碼可以參考.例如之前建立的OPENCV 做影像識別或是語音辨識都可以透過Python做到
,而只要再透過Pyserial 就可以控制Arduino做出如機器人方面的應用.
而Python本身也有支援強大的網路功能,所以要做到IOT物聯網的功能,如從Arduino端得到感測器的資料再透過Python傳到網路伺服器或是從網路端得到指令透過Python傳給Arduino作一些控制也都是可以的.
Python的功能還不只如此對於統計或是科學方面上的應用也是支援很多的套件可以使用,可以說Python 是功能全面性的程式語言但是又不如C++那樣複雜難懂.最主要的是網路幾乎都可以找到你想要的範例程式碼而且都是開源免費的.
有關這個範例的實際示範及詳細的說明可以觀看底下的影片教學.
底下是本範例的Python &Arduino程式碼.
<Source code in Python>
from time import sleep
import serial
from msvcrt import getch
##==============================================================================
ser =serial.Serial("COM4", 115200, timeout=2) # Establish the connection on a specific port
##==============================================================================
##=======getchar========================
def getchar():
#Returns a single character from standard input
key = getch() ##Get byte ex: b'a'
key_num=ord(key) ##convert byte to integer 97
key_chr=chr(key_num) ##convert integer to char 'a'
return key_num
##====================================
##======Write Serial Command to arduino============
def SerialWrite(command):
ser.write(cmd)
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()
##====================================
##=======Get Ready================
print("Connecting to Arduino.....")
for i in range (1,10):
rv=ser.readline()
print("Loading...")
#Debug print (rv) # Read the newest output from the Arduino
print (rv.decode("utf-8"))
ser.flushInput()
sleep(1) # Delay for one tenth of a secon
Str=rv.decode("utf-8")
#Debug print(Str[0:5])
if Str[0:5]=="Ready":
print("Get Arduino Ready !")
break
##------------------------------------------------------
print("==================================")
##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)
##===Get char from keyboard then send to arduino and get it back to print in screen==
while True:
chr_num = getchar()
cmd=(chr(chr_num).encode('utf-8'))
SerialWrite(cmd)
if chr_num==27: ##ESC
break
ser.close()
<Source code in Arduino>
//*****************************************************************************
//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);
}
}
see more:使用python與arduino連接控制LED之GUI圖形介面
http://arbu00.blogspot.tw/2016/07/pythonarduinoledgui.html
加入阿布拉機的3D列印與機器人的FB粉絲團
https://www.facebook.com/arbu00/
Scan QRcode to join FB Fans.