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()
{
Serial.begin(115200);
}
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;
i++;
}
//Just for the sake, print the array contents
for(j = 0; j < i; j++)
{
Serial.print(byteArray[j],HEX);
}
//Check for first two bytes
if( (byteArray[0] == 0x31) && (byteArray[1] == 0x32) )
{
Serial.println("Verified.");
}
}
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
1 Answer 1
So, as result of Edgar Bonet's good remark, change
int i=0 , j=0;
to
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.
-
1The 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– Edgar Bonet2017年07月09日 20:31:32 +00:00Commented Jul 9, 2017 at 20:31
-
@EdgarBonet That was also what I meant, so I rephrased the line. Thank you for the notification.Michel Keijzers– Michel Keijzers2017年07月09日 21:59:34 +00:00Commented Jul 9, 2017 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.zeuschyant8– zeuschyant82017年07月11日 01:29:29 +00:00Commented Jul 11, 2017 at 1:29
i
to 0, thus always writing into the first cell of your array.loop()
run and your array has never more than one characters in it, so your comparison for two elements always fails.