步驟1:在計算機上安裝Python IDLE
如果您要已經(jīng)在計算機中安裝了Python IDLE。如果是,請轉(zhuǎn)到步驟2,否則請按照以下說明進行操作:
1。轉(zhuǎn)到python網(wǎng)站并下載(此處)。
2。完成后,繼續(xù)進行安裝,方法是保留默認情況下安裝python的目錄。
注意:即使您的計算機運行在64位系統(tǒng)上,由于與Arduino庫的兼容性不足,您也可以使用32位Python本身。
步驟3:安裝PySerial
PySerial是一個Python API模塊,用于向Arduino或任何其他微控制器讀取和寫入串行數(shù)據(jù)。要在Windows上安裝,只需訪問PySerial的下載頁面,然后按照以下步驟操作:
1。從上面的鏈接下載PySerial。
2。通過將設置保留為默認值來安裝它。您應該確保Pyserial可以正常運行;為此,請輸入:
import serial
(如果沒有)沒有遇到任何錯誤,所以您的狀態(tài)很好,否則我建議您檢查安裝和Python IDLE擴展。
步驟4:Python代碼
首先,我們需要一個簡單的程序來使Python通過串行端口發(fā)送數(shù)據(jù)。
import serial #Serial imported for Serial communication
import time #Required to use delay functions
ArduinoUnoSerial = serial.Serial(‘com15’,9600) #Create Serial port object called ArduinoUnoSerialData time.sleep(2) #wait for 2 secounds for the communication to get established
print ArduinoUnoSerial.readline() #read the serial data and print it as line
print (“You have new message from Arduino”)
while 1: #Do this forever
var = raw_input() #get input from user
if (var == ‘1’): #if the value is 1
ArduinoUnoSerial.write(‘1’) #send 1 to the arduino‘s Data code
print (“LED turned ON”)
time.sleep(1)
if (var == ’0‘): #if the value is 0
ArduinoUnoSerial.write(’0‘) #send 0 to the arduino’s Data code
print (“LED turned OFF”)
time.sleep(1)
if (var == ‘fine and you’): #if the answer is (fine and you)
ArduinoUnoSerial.write(‘0’) #send 0 to the arduino‘s Data code
print (“I’m fine too,Are you Ready to !??!”)
print (“Type 1 to turn ON LED and 0 to turn OFF LED”)
time.sleep(1)
步驟5:Arduino代碼
要從Python啟動與Arduino的連接,我們首先必須確定Arduino處于哪個COM端口。正如我在上圖中通知的那樣,此任務是由Ardunio編程環(huán)境簡單完成的。
int data;
int LED=13;
void setup() {
Serial.begin(9600); //initialize serial COM at 9600 baudrate
pinMode(LED, OUTPUT); //declare the LED pin (13) as output
digitalWrite (LED, LOW); //Turn OFF the Led in the beginning
Serial.println(“Hello!,How are you Python ?”);
}
void loop() {
while (Serial.available()) //whatever the data that is coming in serially and assigning the value to the variable “data”
{
data = Serial.read();
}
if (data == ‘1’)
digitalWrite (LED, HIGH); //Turn On the Led
else if (data == ‘0’)
digitalWrite (LED, LOW); //Turn OFF the Led
}
步驟6:獲得支持
責任編輯:wv
-
python
+關(guān)注
關(guān)注
56文章
4807瀏覽量
85041 -
Arduino
+關(guān)注
關(guān)注
188文章
6477瀏覽量
187843
發(fā)布評論請先 登錄
相關(guān)推薦
評論