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

时间:2019-04-01 07:05:11

标签: python-3.x arduino usb pyserial

我在理解串行方式时遇到问题。

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

首先,我使用的是keys.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中则没有。

如果有人需要更多上下文,我可以发布其余代码,但是我已经没有足够的尝试空间了,我将非常感谢您的帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

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