如何在同一个 Python 脚本中读取和写入串行缓冲区?

How can I read and write to the serial buffer in the same Python script?

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

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

时,我都会在本地为键盘生成一个代码

起初,我使用的是 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 中没有。

如果有人需要更多上下文,我可以 post 剩下的代码,但是我 运行 没有什么可以尝试的了,我真的很感激能得到一些帮助。谢谢!

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