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



我在理解串行如何工作时遇到问题。

我正在尝试编写一个循环脚本,该脚本在 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 条件,您的代码应按预期工作

最新更新