Arduino 可以将数字传递给 python 脚本吗?

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",但最后没有 return。

然后您可以使用 int()int.from_bytes() 将其转换为 int,或者直接与它进行比较(带引号)。