简体   繁体   English

Arduino阵列程式设计

[英]Arduino array programming

I am learning Arduino, and I have a question. 我正在学习Arduino,并且有一个问题。 I am currently working on a NFC project and I am stuck. 我目前正在从事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]);
    }
  }
}

When I place the NFC chip on the reader, I am getting an output as 2 then after a delay(1000) I am getting an output 4. The issue I am facing is, if I'm not placing the NFC chip on the reader, after delay(1000) it is skipping to the next value and prints 3 the next time I place the NFC on the reader. 当我将NFC芯片放在阅读器上时,我得到的输出为2,然后在delay(1000)我得到了输出4。我面临的问题是,如果我没有将NFC芯片放在阅读器上, ,在delay(1000)它会跳到下一个值,并在下次我将NFC放在阅读器上时显示3。 But I want to print 8 even after a delay of 1000. I am stuck here. 但是即使延迟1000,我也想打印8。我被卡在这里。

You could use a while -loop and only increment when the chip is found: 您可以使用while -loop循环,并且仅在找到芯片时递增:

 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.
    }
  }

Note that myPins could be defined once outside of the loop, which would make the loop faster: 请注意,可以在循环外定义一次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.
    }
  }

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

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