【问题标题】:Using Python and Arduino to change delay of light bulb via Serial使用 Python 和 Arduino 通过串行更改灯泡的延迟
【发布时间】:2019-01-02 22:07:10
【问题描述】:

我在 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(); 函数获得错误类型的输入时,它就会将其解释为零。

【问题讨论】:

    标签: python-3.x arduino pyserial


    【解决方案1】:

    documentation 说:

    如果超时(参见 Serial.setTimeout())发生时没有读取到有效数字,则返回 0;

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

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

    尝试打印出 arduino 接收到的值。它应该告诉您正在发生的事情以及解决问题的方向。

    【讨论】:

    • 原来 Serial.parseInt() 排除了要通过串行发送的字符串值。因此,理想情况下,您将通过arduinoData.write(str(10).encode('ascii')发送数字并通过首先serialData = Serial.parseInt()接收它,其中serialData的定义如下long serialData;,然后写入Yourint = serialData,其中Yourint的定义如下int Yourint;
    猜你喜欢
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 2020-08-23
    • 1970-01-01
    • 1970-01-01
    • 2011-08-06
    • 1970-01-01
    • 2022-01-10
    相关资源
    最近更新 更多