Reputation: 51
I am receiving a packet like 0xFA5D0D01. Now i want to parce it like
FA is Header1 5D is Header2 0D is length and 01 is checksum. const int data_availabe = Serial.available();
I am able to write to serial port but not able to parce it like if i received FA is then print received Header1
const int data_availabe = Serial.available();
if (data_availabe <= 0)
{
return;
}
const int c = Serial.read();
Serial.print("Receive Status: ");
Serial.println(STATE_NAME[receiveState]);
Serial.print(c, HEX);
Serial.print(" ");
if (isprint(c)) //isprint checks whether it is printable character or not (e.g non printable char = \t)
{
Serial.write(c);
}
Serial.println();
Serial.println(receiveState);
switch (receiveState)
{
case WAITING_FOR_HEADER1:
if (c == HEADER1)
{
receiveState = WAITING_FOR_HEADER2;
}
break;
case WAITING_FOR_HEADER2:
if (c == HEADER2)
{
receiveState = WAITING_FOR_LENGTH;
}
break;
}
Where receiveState is enum changing as we are getting exptected data..
Upvotes: 1
Views: 490
Reputation: 3070
I assume the Arduino is receiving data from USB.
What is the if (data available <= 0)
doing? If you want want to read data from the serial port while it is avalaible, you should better do if (Serial.avalaible() > 1)
and then Serial.read()
inside the {}
.
If you initialize a const
you won't be able to change its value over time...
What is readString
and how is it initialized?
Have you tried to Serial.print(c)
to see what's inside?
Once again, it would be easier for us if you could give us more context on why and when this piece of code is running.
EDIT:
#define HEADER_1 0xFA // here you define your headers, etc. You can also use variables.
uint8_t readByte[4]; // your packet is 4 bytes long. each byte is stored in this array.
void setup() {
Serial.begin(9600);
}
void loop() {
while (Serial.avalaible() > 1) { // when there is data avalaible on the serial port
readByte[0] = Serial.read(); // we store the first incomming byte.
delay(10);
if (readByte[0] == HEADER_1) { // and check if that byte is equal to HEADER_1
for (uint8_t i = 1 ; i < 4 ; i++) { // if so we store the 3 last bytes into the array
readByte[i] = Serial.read();
delay(10);
}
}
}
//then you can do what you want with readByte[]... i.e. check if readByte[1] is equal to HEADER_2 and so on :)
}
Upvotes: 3