为什么这个bool会改变?

时间:2016-10-05 15:37:08

标签: c++ arduino

如果没有为此发布完整的源代码,任何人都可以看到为什么bool正在更改值?

const int redLed = 31;
const int greenLed =  33;
const int blueLed = 35;
const int irSensor = 2;
const int doorRelayPin = 14;
bool isDenied = false;
byte inputCard[4];
char cardID[4];
char passCode[10];
int passCount = 0;
char masterCode[10] = "1";

void loop(){
    if(isPanic){
      panicCounter++;
      int interval = panicCounter % 2000;
      Serial.println(interval);
      if (interval == 0){
        tryPost();
      }
   }else{
      if (!digitalRead(doorRelayPin) && !isDenied){
        greenSolid();
      }else if(digitalRead(doorRelayPin) && !isDenied){
        blueSolid();
        t.stop(unlock);
      }
   }
   Serial.print("isDenied bool: ");
   Serial.println(isDenied);
}

下一段相关代码可以帮助您理解输出...

Serial.println(F("Scanned PICC's UID on reader 1:"));
for (int i = 0; i < 4; i++) {  //
  inputCard[i] = idReader.uid.uidByte[i];
  Serial.print(inputCard[i], HEX);
}
Serial.println("");
idReader.PICC_HaltA(); // Stop reading
getCardID();    // Get data ready
return 1;  

正如您所看到的,我没有更改此布尔ANYWHERE的值,但循环函数中的串行输出和我的if statement表示值已更改。在阅读和RFID卡的PICC功能期间似乎正在发生这种情况。请指教,谢谢!

下面的串行输出。

isDenied bool: 0
isDenied bool: 0
isDenied bool: 0
isDenied bool: 0
isDenied bool: 0
isDenied bool: 0
Scanned PICC's UID on reader 1:
F539A76B
isDenied bool: 54
ip=10.10.1.50&passcode=&rfid=f539a76b
connecting...Connected
disconnecting.
grant 10.10.1.50
Access Granted.
isDenied bool: 54
isDenied bool: 54
isDenied bool: 54
isDenied bool: 54
isDenied bool: 54
isDenied bool: 54

更奇怪的是,如果我试图通过在if(isPanic)语句正上方的循环函数中执行此操作来“破解”此问题,则bool永远不会更改。但是这些新的if语句也永远不会满足,输出日志不会显示这两个测试中的任何一个Serial.println

if (isDenied == 54){
  isDeniedBoolRecoverCounter++;
  Serial.println("In this");
}
if (isDeniedBoolRecoverCounter > 10){
   Serial.println("In the other one");
   isDenied = false;
   isDeniedBoolRecoverCounter = 0;
}

1 个答案:

答案 0 :(得分:0)

好吧,你们是对的。这是与cardID[]变量有关的缓冲区溢出问题。最初它被初始化为cardID[4] = "";在将其缩小到确认问题之后,我尝试cardID[] = "";确实解决了这个问题,但是isDenied bool仍在暂时改变,尽管它恢复正常。最终的正确声明是char cardID[8] = "";

我仍然围绕着char数组变量以及如何声明/初始化它们。

我的猜测是我试图分配&#34; f539a76b&#34;到一个(4)字符char数组与行...

sprintf(cardID, "%02x%02x%02x%02x", inputCard[0], inputCard[1], inputCard[2], inputCard[3]);

实际上我需要一个(8)字符数组。