简体   繁体   English

Arduino-C++ Bool 不会从假变为真

[英]Arduino-C++ Bool Not Changing From False To True

I am currently trying to make an NFC Door Lock and I am trying to make it so when the door is locked it knows and will unlock the door with the right NFC card and vice versa.我目前正在尝试制作 NFC 门锁,并且我正在尝试制作它,以便当门被锁定时,它知道并会使用正确的 NFC 卡解锁门,反之亦然。 I have created the bool locked and made it = false.我已经创建了 bool 锁定并使其 = false。 When I unlocked the door I have made it so that it will change bool locked from false to true although that doesn't work and the NFC card continues to lock the door every time.当我打开门时,我已经做到了,它会将 bool 锁定从 false 更改为 true,尽管这不起作用并且 NFC 卡每次都继续锁门。

NFC Card Read Area: NFC读卡区:


    if ( ! mfrc522.PICC_IsNewCardPresent())
        return;

    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial())
        return;

    // Show some details of the PICC (that is: the tag/card)
    bool locked = false;
    if(locked == false)
    {
    Serial.print(F("Card UID:"));
    dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
    byte valid[4] = { 0xEB, 0xA6, 0xE9, 0x21 };
    if (memcmp(valid, mfrc522.uid.uidByte, mfrc522.uid.size) == 0) {
        Serial.print("Door Locked"); 
        int motorPin = 3;
        digitalWrite(motorPin, HIGH); // turns the motor ON
        delay(5000);
        digitalWrite(motorPin, LOW); // turns the motor OFF
        bool locked = true;
    }}
    if(locked == true)
    {
    Serial.print(F("Card UID:"));
    dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
    byte valid[4] = { 0xEB, 0xA6, 0xE9, 0x21 };
    if (memcmp(valid, mfrc522.uid.uidByte, mfrc522.uid.size) == 0) {
        Serial.print("Door Unlocked");
        int motorPin = 3;
        digitalWrite(motorPin, HIGH); // turns the motor ON
        delay(5000);
        digitalWrite(motorPin, LOW); // turns the motor OFF
        bool locked = false;
    }}
    Serial.println();
    Serial.print(F("PICC type: "));
    MFRC522::PICC_Type piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
    Serial.println(mfrc522.PICC_GetTypeName(piccType));

Full Code:完整代码:

#include <SoftwareSerial.h>
#include <ArduinoBlue.h>
#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9           // Configurable, see typical pin layout above
#define SS_PIN          10          // Configurable, see typical pin layout above



const unsigned long BAUD_RATE = 9600;

// The bluetooth tx and rx pins must be supported by software serial.
// Visit https://www.arduino.cc/en/Reference/SoftwareSerial for unsupported pins.
// Bluetooth TX -> Arduino D8
const int BLUETOOTH_TX = 8;
// Bluetooth RX -> Arduino D7
const int BLUETOOTH_RX = 7;

int prevThrottle = 49;
int prevSteering = 49;
int throttle, steering, sliderVal, button, sliderId;

SoftwareSerial bluetooth(BLUETOOTH_TX, BLUETOOTH_RX);
ArduinoBlue phone(bluetooth); // pass reference of bluetooth object to ArduinoBlue constructor

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.

// Number of known default keys (hard-coded)
// NOTE: Synchronize the NR_KNOWN_KEYS define with the defaultKeys[] array
#define NR_KNOWN_KEYS   8
// Known keys, see: https://code.google.com/p/mfcuk/wiki/MifareClassicDefaultKeys
byte knownKeys[NR_KNOWN_KEYS][MFRC522::MF_KEY_SIZE] =  {
    {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, // FF FF FF FF FF FF = factory default
    {0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5}, // A0 A1 A2 A3 A4 A5
    {0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5}, // B0 B1 B2 B3 B4 B5
    {0x4d, 0x3a, 0x99, 0xc3, 0x51, 0xdd}, // 4D 3A 99 C3 51 DD
    {0x1a, 0x98, 0x2c, 0x7e, 0x45, 0x9a}, // 1A 98 2C 7E 45 9A
    {0xd3, 0xf7, 0xd3, 0xf7, 0xd3, 0xf7}, // D3 F7 D3 F7 D3 F7
    {0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}, // AA BB CC DD EE FF
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}  // 00 00 00 00 00 00
};


// Setup code runs once after program starts.
void setup() {
    // Start serial communications.
    // The baud rate must be the same for both the serial and the bluetooth.
    SPI.begin(); 
    Serial.begin(BAUD_RATE);
    while (!Serial);            // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
    mfrc522.PCD_Init();         // Init MFRC522 card
    Serial.println(F("Try the most used default keys to print block 0 of a MIFARE PICC."));
    bluetooth.begin(BAUD_RATE);
    delay(100);

    Serial.println("setup complete");
}

void dump_byte_array(byte *buffer, byte bufferSize) {
    for (byte i = 0; i < bufferSize; i++) {
        Serial.print(buffer[i] < 0x10 ? " 0" : " ");
        Serial.print(buffer[i], HEX);
    }
}

bool try_key(MFRC522::MIFARE_Key *key)
{
    bool result = false;
    byte buffer[18];
    byte block = 0;
    MFRC522::StatusCode status;

    // Serial.println(F("Authenticating using key A..."));
    status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, key, &(mfrc522.uid));
    if (status != MFRC522::STATUS_OK) {
        // Serial.print(F("PCD_Authenticate() failed: "));
        // Serial.println(mfrc522.GetStatusCodeName(status));
        return false;
    }

    // Read block
    byte byteCount = sizeof(buffer);
    status = mfrc522.MIFARE_Read(block, buffer, &byteCount);
    if (status != MFRC522::STATUS_OK) {
        // Serial.print(F("MIFARE_Read() failed: "));
        // Serial.println(mfrc522.GetStatusCodeName(status));
    }
    else {
        // Successful read
        result = true;
        Serial.print(F("Success with key:"));
        dump_byte_array((*key).keyByte, MFRC522::MF_KEY_SIZE);
        Serial.println();
        // Dump block data
        Serial.print(F("Block ")); Serial.print(block); Serial.print(F(":"));
        dump_byte_array(buffer, 16);
        Serial.println();
    }
    Serial.println();

    mfrc522.PICC_HaltA();       // Halt PICC
    mfrc522.PCD_StopCrypto1();  // Stop encryption on PCD
    return result;
}

void loop() {

    button = phone.getButton();

    // Returns the text data sent from the phone.
    // After it returns the latest data, empty string "" is sent in subsequent.
    // calls until text data is sent again.
    String str = phone.getText();

    // Display button data whenever its pressed.
    if (button == 1) {
        Serial.print("Door Locked");
    }

        // Display button data whenever its pressed.
    if (button == 0) {
        Serial.print("Door Unlocked");
        int motorPin = 3;
        digitalWrite(motorPin, HIGH); // turns the motor ON
        delay(5000);
        digitalWrite(motorPin, LOW); // turns the motor OFF



    }


    // Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.

    if ( ! mfrc522.PICC_IsNewCardPresent())
        return;

    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial())
        return;

    // Show some details of the PICC (that is: the tag/card)
    bool locked = false;
    if(locked == false)
    {
    Serial.print(F("Card UID:"));
    dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
    byte valid[4] = { 0xEB, 0xA6, 0xE9, 0x21 };
    if (memcmp(valid, mfrc522.uid.uidByte, mfrc522.uid.size) == 0) {
        Serial.print("Door Locked"); 
        int motorPin = 3;
        digitalWrite(motorPin, HIGH); // turns the motor ON
        delay(5000);
        digitalWrite(motorPin, LOW); // turns the motor OFF
        bool locked = true;
    }}
    if(locked == true)
    {
    Serial.print(F("Card UID:"));
    dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
    byte valid[4] = { 0xEB, 0xA6, 0xE9, 0x21 };
    if (memcmp(valid, mfrc522.uid.uidByte, mfrc522.uid.size) == 0) {
        Serial.print("Door Unlocked");
        int motorPin = 3;
        digitalWrite(motorPin, HIGH); // turns the motor ON
        delay(5000);
        digitalWrite(motorPin, LOW); // turns the motor OFF
        bool locked = false;
    }}
    Serial.println();
    Serial.print(F("PICC type: "));
    MFRC522::PICC_Type piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
    Serial.println(mfrc522.PICC_GetTypeName(piccType));

    // Try the known default keys
    MFRC522::MIFARE_Key key;
    for (byte k = 0; k < NR_KNOWN_KEYS; k++) {
        // Copy the known key into the MIFARE_Key structure
        for (byte i = 0; i < MFRC522::MF_KEY_SIZE; i++) {
            key.keyByte[i] = knownKeys[k][i];
        }
        // Try the key
        if (try_key(&key)) {
            // Found and reported on the key and block,
            // no need to try other keys for this PICC
            break;
        }

        // http://arduino.stackexchange.com/a/14316
        if ( ! mfrc522.PICC_IsNewCardPresent())
            break;
        if ( ! mfrc522.PICC_ReadCardSerial())
            break;
    }
}

Within the scope of your if-statements you create another local variable bool locked and you do not reassign the one which is used for checking the current state.在您的 if 语句的范围内,您创建另一个局部变量bool locked并且您不会重新分配用于检查当前状态的变量。

So without deeper looking on the rest of the code you need to assign locked with the proper value instead of defining another locked-variable:因此,无需深入查看其余代码,您需要使用适当的值分配locked而不是定义另一个锁定变量:

locked = false; 

instead of代替

bool locked = false;

Clarification:澄清:

int a = 0;

if (1)
{
    int a = 42; // this is not 'a' from above
    std::cout << "value of a: " << a << "\n";
} // here ends the lifetime of the inner 'a'

std::cout << "value of a: " << a << "\n";

Output:输出:

value of a: 42
value of a: 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM