[英]Can Arduino communicate a number to a python script?
好的,我需要做的是:
當我按下 Arduino 上的按鈕時,它會向 PC 發送一個數字。
int button1 = 0;
int button2 = 0;
void setup() {
pinMode(2, INPUT);
pinMode(3, INPUT);
}
void loop() {
button1 = digitalRead(2);
button2 = digitalRead(3);
if (button1==1) Serial.println(13);
else if (button2==1) Serial.println(14);
}
然后,python 腳本讀取該信號,並根據接收到的數字執行不同的操作。
import keyboard
import serial
ser = serial.Serial("COM7", 9600)
while True:
if ser.read == 13:
keyboard.press_and_release ('f13')
while True:
if ser.read != 13:
break
if ser.read == 14:
keyboard.press_and_release ('f14')
while True:
if ser.read != 14:
break
ser.close()
我想說我是一個新手,這可能很容易做到,但我嘗試了這個和其他版本,但它從來沒有用過。
我嘗試的另一件事是:
import keyboard
import serial
ser = serial.Serial("COM7", 9600, timeout=.1)
while True:
data = ser.readline()[:-2]
if data:
print (data)
if data == 13:
print(13)
keyboard.press_and_release ('f13')
while True:
if ser.read != 13:
break
if data == 14:
print(14)
keyboard.press_and_release ('f14')
while True:
if ser.read != 14:
break
ser.close()
有了這個,它確實用print (data)
打印了一些東西,它打印了b'13'
,但是寫if data == "b'13'":
沒有任何改變。
在此先感謝您的幫助。
Arduino 正在發送帶有編號的EOL
,您必須將其剝離。
嘗試類似data = data.decode("utf-8").rstrip()
的東西,它應該給你“13”而最后沒有返回。
然后,您可以使用int()
或int.from_bytes()
將其轉換為int
,或者直接與它進行比較(帶引號)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.