代码之家  ›  专栏  ›  技术社区  ›  bharath

Arduino阵列编程

  •  -1
  • bharath  · 技术社区  · 8 年前

    我正在学习Arduino,我有一个问题。我目前正在从事一个NFC项目,我被卡住了。

    #include <Wire.h>
    #include <PN532_I2C.h>
    #include <PN532.h>   
    #include <NfcAdapter.h>
    
    PN532_I2C pn532_i2c(Wire);
    NfcAdapter nfc = NfcAdapter(pn532_i2c);  
    int i;
    
    void setup(void) {
      Serial.begin(115200);
      nfc.begin();
    }
    
    void loop() {
     for (i = 0; i < 5; i = i + 1){
        delay(1000);
        if(nfc.tagPresent()){
          int myPins[] = {2, 4, 8, 3, 6};
          Serial.println(myPins[i]);
        }
      }
    }
    

    当我把NFC芯片放在读卡器上时,我得到的输出是2,然后在 delay(1000) 我得到一个输出4。我面临的问题是,如果我没有在读卡器上放置NFC芯片 延迟(1000) 它跳转到下一个值,并在下次我将NFC放在读卡器上时打印3。但我想打印8,即使延迟了1000次。我被困在这里了。

    1 回复  |  直到 8 年前
        1
  •  2
  •   BobMorane    8 年前

    你可以使用 while -回路,仅当找到芯片时递增:

     int i = 0;
    
     while (i < 5)
     {
        delay(1000);
        if(nfc.tagPresent())
        {
          int myPins[] = {2, 4, 8, 3, 6};
          Serial.println(myPins[i]);
          i = i + 1; // increment only if tag is present.
        }
      }
    

    请注意 myPins 可以在循环外部定义,这将使循环更快:

     int i = 0;
     int myPins[] = {2, 4, 8, 3, 6};
    
     while (i < 5)
     {
        delay(1000);
        if(nfc.tagPresent())
        {
          Serial.println(myPins[i]);
          i = i + 1; // increment only if tag is present.
        }
      }