I'm writing some code to exchange data frames between an arduino and a python program, based on Robin2's serial input basics. During operation, the arduino will send back data which type may vary depending on the command sent by the pc. Because of that, my code has a type inconsistency between two blocks and I not sure how to solve it.
The code below isn't functional but should give you an idea of what I'm trying to do.
const uint8_t MAXLEN = 32;
void loop() {
uint8_t tx_buffer[MAXLEN];
uint8_t tx_len = 0;
uint8_t rx_buffer[MAXLEN];
uint8_t rx_len = 0;
get_message(rx_buffer, &rx_len) // dataframe is received from Serial and stored in a buffer
uint8_t cmd_code = rx_buffer[1]; // command code retrieved from dataframe
switch (cmd_code) { // command code says what action the arduino should perform
case 0:
// do stuff....
result = get_result_1(); // result is a given type
break;
case 1:
// do other stuff....
result = get_result_2(); // result is another given type
break;
/// ....
}
encode_data(result, rslt_len, tx_buffer, &tx_len);
// void encode_data(uint8_t input[], uint8_t in_len, uint8_t output[], uint8_t *out_len)
send_message(tx_buffer, tx_len); // send contents of tx_buffer through Serial
}
In this example, the arduino receives a message through Serial, does some tasks according to
the transmitted command code, and returns a result value. The result can have different types (char array, int, int array, float, etc), but should ultimately be transmitted through Serial as an array of uint8_t.
A few observations:
-
encode_data
can be overloaded for various data types, so I thought of declaring aresult
inside each case with the return type corresponding to eachget_result_x()
. The arduino compiler doesn't seem to mind, but I'm pretty sure this is bad practice... - Using
(uint8_t*)result
as argument also seems to work pretty well with the data types I am using so far, butresult
still has an inconsistent type inside the switch. Is it possible to directly cast the return value ofget_result_x()
to uint8_t* ? - Placing
encode_data
inside each case would likely solve my problem, but it seems like an unnecessary repetition of code which I would like to avoid if possible. I feel it will become a hassle to maintain as I add more command codes.
If it was python, the type of result
would not be an issue, at least for the current scope.. but with C I'm not sure how to proceed ... Any suggestions?