Arduino array programming

bharath Source

I am learning Arduino, and I have a question. I am currently working on a NFC project and I am stuck.

#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. But I want to print 8 even after a delay of 1000. I am stuck here.

c++arduino

Answers

answered 5 days ago BobMorane #1

You could use a while-loop and only increment when the chip is found:

 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:

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

comments powered by Disqus