I'm writing a program to read bytes from serial channel, copy those into an array and then do some verification on those copied numbers.

I'm able to read and copy bytes into an array of bytes. However, I'm facing an issue with the verification of those bytes.

Here's the code I've written:

#include <SoftwareSerial.h>

void setup() 

void loop() 
    char charRead = 0x00u;
    byte byteArray[10];
    int i=0 , j=0;

    //Clear the array contents
    for(j = 0; j < 10u; j++)
       byteArray[j] = 0x00u;

    //Wait for data on serial channel
    while(Serial.available() > 0)
       //Copy bytes received into array
       charRead      = Serial.read();
       byteArray[i] = (byte)charRead;

    //Just for the sake, print the array contents
    for(j = 0; j < i; j++)

    //Check for first two bytes
    if( (byteArray[0] == 0x31) && (byteArray[1] == 0x32) )

To test this program, I entered "12345" (without quotes) on the serial monitor which gave me an output as "3132333435" since I'm printing the contents of the array in HEX format.

What I'm not being able to understand is even if this output shows that the first two bytes in the array are 0x31 & 0x32 respectively, why not the verification logic of those two bytes is getting executed? If it would, then the string 'Verified' would get printed on the output.

Am I doing something wrong here with Serial.read() or some typecasting?

I'm running this on an Arduino Uno

  • 2
    You are continuously resetting i to 0, thus always writing into the first cell of your array. – Edgar Bonet Jul 9 '17 at 17:07
  • You are probably reading one character per loop() run and your array has never more than one characters in it, so your comparison for two elements always fails. – gre_gor Jul 11 '17 at 1:06

So, as result of Edgar Bonet's good remark, change

int i=0 , j=0;


int j = 0;

and define

int i = 0;

Outside the loop (as a global variable).

Also it is quite dangerous to define the length of the array as 10, while not checking for writing over the boundary of the array. What if you receive more bytes? The application might crash or give unpredictable behavior.

  • 1
    The problem is not the size of the array. 10 bytes may be just fine for the intended application. The problem is not checking for overflow. – Edgar Bonet Jul 9 '17 at 20:31
  • @EdgarBonet That was also what I meant, so I rephrased the line. Thank you for the notification. – Michel Keijzers Jul 9 '17 at 21:59
  • I made some more mistakes too - declaring the array local inside loop() and also clearing it every time the loop runs. Thanks all. – Sushant Shidore Jul 11 '17 at 1:29

This site is temporarily in read only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .