ARDUINO: Combine all the characters of a serial input

Viewed 181

I'm trying to check if an entered response (input from the serial monitor) matches a certain item in an array.

When the user enters his response trought digital.read(), the program checks if it corresponds to, in this case, the first item of an array (CARD_ID[0]).

However, the response is split into 4 different parts, it does the checking for every character of the response. How can I take the entire response and then do the checking for it?

The program works fine if I want to check the response with the items in the array NAME because the items are 1 character long.

char CARD_ID[] = {'0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111'};
char NAME[16] = {'A', 'B', 'C', 'D', 'E', 'F', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q'};
int i = 0;
char reponse;

void setup() {
  Serial.begin(9600);
}

void loop() {
  if (Serial.available() > 0) {
    reponse = Serial.read();
    if (reponse == CARD_ID[i]){
        Serial.println("Yes");
    }
    else {
        Serial.println("No");
    }
  }
}

Serial Monitor output:

When 0000 is entered:

No
No
No
No

Expected output:

Yes
1 Answers

You should string all the Serial.read() outputs (single chars) together until you get a return (entered by the user), so you know you have the whole response before checking it against the array.

Alternatively, use Serial.readStringUntil() with '\r' as the termination character.

Also, if (reponse == CARD_ID[i]) should be in a loop; i never gets increased so it only checks against the array's first element.

Also, you are comparing response with CARD_ID[i] using ==, which may not work.

Also, use double quotes for the values in the CARD_ID[i] array.

Related