I am having problems running some code that I succesully tested on the arduino mega. The code receives 5 bytes ('&','@', uint8, uint16) and parses them using a union with a struct inside. This works well on the arduino mega.
Any ideas on how I can solve this bug?
I'm working from Windows 10, and I sending the data from Matlab
Any ideas on how I can solve this bug?
I'm working from Windows 10, and I sending the data from Matlab
Code:
#define A_START '&'
#define B_START '@'
#define HEAD_LENGTH 2
#define MSG_LENGTH 3
#define BAUDRATE 115200
int cnt = 0; // serial data counter
// Struct for Data Conversion
typedef struct {
union {
struct {
uint8_t channel;
uint16_t val;
};
char data[3];
};
} convertor;
convertor packet;
enum State { st_h1, st_h2, st_data}; // not used
enum State fromState = st_data; // not used
void setup()
{
// put your setup code here, to run once:
Serial.begin(BAUDRATE);
Serial1.begin(BAUDRATE);
Serial1.println("Check!");
}
void loop()
{
char msg;
while (Serial.available())
{
msg = Serial.read(); cnt++;
Serial1.println(msg);
// check if A_START
if ((msg == A_START) && (cnt == 1))
{
cnt++;
}
// check if B_START
else if ((msg == B_START) && (cnt == 2))
{
cnt++;
}
// read data
else if (cnt == 3)
{
Serial.readBytes(packet.data, 3);
Serial1.print("Channel: "); Serial1.println(packet.channel);
uint16_t val = packet.val;
Serial1.print("TEST: "); Serial1.println(val);
// Serial1.print("Value: "); Serial1.println(packet.val);
// Serial1.print("Value: "); Serial1.println(packet.data[1]);
// Serial1.print("Value: "); Serial1.println(packet.data[2]);
cnt = 0;
}
// force search for heard
else
{
cnt = 0;
}
}
}