i'm trying to send data from a C++ program over serial communication to an Arduino. I formed a struct for sending the data as an object:
typedef struct
{
double width;
double height;
bool passBoard;
} MachineParameters;
I'm using this Serial library: http://wjwwood.github.com/serial/ for sending the data like this:
MachineParameters mp;
mp.width = 100;
mp.height = 200;
mp.passBoard = true;
ser.write((const uint8_t *)&mp, sizeof(mp));
The library makes it possible to send the data as uint8_t, std::vector or std::string.
The Arduino does receive data, but i don't know how to parse the data into the struct. I'm using the same struct as in the cpp code.
// In Arduio
MachineParameters mp;
int byte_size = 24;
loop() {
if(Serial.available() >= 24) {
Serial.readBytes((char*) &mp , 24);
}
}
// Goal: Read received mp data just like
// mp.width or mp.height
After hours of trying, i still cannot figure it out, how to send this struct to the arduino successfully. Is there another way of sending this data to the arduino? It worked sending the data as string, but that did not seem right.
I am pretty new to programming with C++, so please excuse any obvious questions...
Thank you for helping!
UPDATE: Working solution below
After a view more tries and thanks to your tips, i figured it out. Here is the code, which worked for me. I found out that my problem was the wrong byte size, used for parsing the buffer. The size of the struct in C++ is 12
, whereas on the arduino it's 9
. Using the original size (12) for parsing the buffer on the Arduino, the struct was parsed correctly.
/* --- C++ CODE --- */
typedef struct
{
double width;
double height;
bool passBoard;
} MachineParameters;
// sizeof(MachineParameters) returns 12.
MachineParameters mp;
mp.width = 11.1;
mp.passBoard = false;
mp.height = 22.2;
ser.write((uint8_t *)&mp, sizeof(mp));
/* --- END OF C++ --- */
/* --- Arduino Code --- */
#define BYTE_SIZE 12
char messageBuffer[BYTE_SIZE];
typedef struct
{
double width;
double height;
bool passBoard;
} MachineParameters;
MachineParameters mp;
void setup() {
Serial.begin(9600);
}
void loop() {
if (Serial.available() >= BYTE_SIZE) {
Serial.readBytes(messageBuffer , BYTE_SIZE);
memcpy(&mp, &messageBuffer, BYTE_SIZE);
// mp.width returns 11.1
// Success :)
}
}
/* --- END OF ARDUINO --- */