【问题标题】:How can I read and write to the serial buffer in the same Python script?如何在同一个 Python 脚本中读取和写入串行缓冲区?
【发布时间】:2019-04-01 07:05:10
【问题描述】:

我无法理解串行的工作原理。

我正在尝试编写一个循环脚本,该脚本在 Python 中生成代码,读取输入到 Arduino 键盘的六位数代码的串行缓冲区,将其发送回 Python,根据 postgreSQL 数据库中的代码检查它并返回一个值(1 表示匹配,0 表示不匹配)。我想将二进制值发送到 Arduino 并触发线性伺服。当我运行我编写的 Python 循环时,它会按照我的预期运行,直到我得到从 SQL 数据库返回的值。该值似乎没有写入串行缓冲区,因此 Arduino 循环永远不会触发线性伺服。为了简化测试,每次循环运行时,我都会在本地为键盘生成一个代码。

起初,我使用的是keypad.h 函数waitForKey(),它是阻塞的。我认为阻塞阻止了 Arduino 循环注册更新的值和操作伺服。我将其更改为 getKey(),但该功能仍然无法正常工作。我尝试了不同的编码方法并编写了不同类型的数据(字符和数字),但似乎没有任何效果。

这是 Python 代码中最相关的部分:

if (txStage == '0'):
        #genCode = search_ChatValue("access_code","demo") #Find the value in the database table
        time.sleep(10)
        while (ser.inWaiting() > 0):
            codeDigit = ser.readline(9)
            codeDigit = codeDigit.decode()
            codeDigit = codeDigit[0:6]
        ser.flush()
        print(codeDigit)
        attemptCode(codeDigit, "demo") #check the entered code against the database code
        doorVer = codeResult("demo") #Check if the code was correct
        print(doorVer)
        if (doorVer == "Success! You may now access your SafeDrop."): #if the code is correct
            lockVer = '1' #variable to be sent to the Arduino
            print("lock status is: " + str(lockVer))
            ser.flush() #flush the serial buffer to ensure it is empty
            lockVer = lockVer.encode("utf-8")
            ser.write(lockVer) #write to Arduino
            time.sleep(10) #wait for lock to open
        #time.sleep(5)

这是 Arduino 代码:

void loop(){
  char pass[6]; 
  char lockVer = '0';
  int sensorValue = analogRead(A0);
  Door(sensorValue);
  door = warning;
  if (Serial.available() > 0){
    lockVer = Serial.read();
  }
  if (lockVer == '0'){
    while (door == 0){
        while (i < 6){
          char key = customKeypad.getKey();
          if (key){
            pass[i] = key;
            lcd.write('*');
            i++;
            if (i == 6){
              delay(500);
              lcd.clear();
              i = 0;
            }
           }
           Serial.println(pass);
           Serial.flush();
        }
      //delay(5000);
      //scaleCheck;
    }
  }
  else{
    Lock(unlock);
    delay(5000);
    Lock(lock);
    delay(5000);
    }
  }

我希望变量 lockVer 会从 0 变为 1,这种变化会被 Arduino 识别,导致线性伺服启动并移动到解锁位置,等待 5 秒,然后移动回到锁定位置位置。相反,Arduino 代码忽略了更改,并继续寻找键盘输入。确认键盘代码可以工作,变量 lockVer 在 Python 中确实从 0 变为 1,只是在 Arduino 中没有。

如果有人需要更多上下文,我可以发布其余代码,但我已经没有东西可以尝试了,我非常感谢一些帮助。谢谢!

【问题讨论】:

  • 看起来您的 arduino 代码卡在了“while(door == 0)”循环中。将其更改为 if 条件,您的代码应该可以按预期工作。
  • 您好 Nitro,感谢您回复我!这正是问题所在。感谢您的帮助!
  • 请将我给出的答案标记为正确答案,以便下一组查看此帖子的人知道这是正确的答案。

标签: python-3.x arduino usb pyserial


【解决方案1】:

看起来您的 arduino 代码卡在了“while(door == 0)”循环中。将其更改为 if 条件,您的代码应该可以按预期工作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-16
    • 2019-06-30
    • 2015-04-10
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 2019-02-28
    • 1970-01-01
    相关资源
    最近更新 更多