使用 Python 和 Arduino 通过串口改变灯泡的延迟

Using Python and Arduino to change delay of light bulb via Serial

我在 Windows 10 64 位上使用 Arduino Mega 和 python 3.7。我正在尝试使用 python 和 pyserial 使灯泡闪烁。我希望灯泡保持亮起 x 时间并关闭 y 时间。我在 python Tkinter 程序中输入值:https://pastebin.com/zkRmcP60 完整代码。在我输入通过以下代码发送到 Arduino 的值后:

import msgpack
import serial
arduionoData = serial.Serial('com3', 9600, timeout=1)
def sendlower(*args):

    try:
            global arduionoData
            arduionoData.write(b"1")
            while arduionoData.readline().decode() != "Send Next":
                pass
            first = int(firstdelay.get())
            arduionoData.write(msgpack.packb(first, use_bin_type=True))
    except ValueError:

        print("Only Positive Integers")

def senduppper(*args):
    try:

        global arduionoData
        arduionoData.write(b"2")
        while arduionoData.readline().decode() != "Send Next":
            pass
        second = int(seconddelay.get())
        arduionoData.write(msgpack.packb(second, use_bin_type=True))

    except ValueError:

        print("Only Positive Integers")

Tkinter 程序执行上述功能访问 Pastebin 以获取整个代码。

首先我指定模式或者它是否会改变开启延迟或关闭延迟。 使用此代码(省略设置和其他代码,请在粘贴箱中查找。)

void readdelay(){
  mode = Serial.parseInt();
  if (mode == 1){
      delay(200);
      Serial.write("Send Next");
      delay1 = Serial.parseInt();
  }else if (mode == 2){
      delay(200);
      Serial.write("Send Next");
      delay2 = Serial.parseInt();  
  }
}
void loop() {
  if (Serial.available() > 0){
     readdelay();
  }
}

现在,如果我将任何正数发送到程序中,它要么完全关闭(当我发送一个数字用于开启延迟时)灯,要么将其打开(当我发送一个数字用于关闭时)延迟)。我的猜测是,每当 Serial.parseInt(); 函数获得错误类型的输入时,它会将其解释为零。

documentation 说:

If no valid digits were read when the time-out (see Serial.setTimeout()) > occurs, 0 is returned;

似乎parseInt失败了,因此延迟设置为0,这就是灯完全打开或关闭的原因。

另一种可能性是 arduino 只接收到第一个字符,这意味着灯切换得如此之快以至于你看不到它。 (问题描述 here

尝试打印出arduino接收到的值。它应该告诉你发生了什么以及解决它的方向。