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