Same issue for me, but this is my solution.
Mapping beween python struct (packed data) and arduino struct is as follows:
Python Arduino
? boolean
i int32_t or uint32_t
f float
Arduino Code:
// The struct we want to send over the serial connection
struct Data {
int32_t timer;
float value2;
uint32_t sensor1;
uint32_t datasize;
};
Data data;
void setup() {
// Initialize the serial connection
Serial.begin(115200);
}
void loop() {
// Create an instance of the Data struct
data.timer = micros();
data.value2 = 3.14;
// read the input on analog pin 0:
data.sensor1 = analogRead(A0);
// Calculate the size of the struct in bytes
size_t size = sizeof(data);
data.datasize = size;
// Allocate a buffer for the packed data
uint8_t *buf = (uint8_t*)malloc(size);
// Pack the data into the buffer
memcpy(buf, &data, size);
// Send the packed data over the serial connection
Serial.write(buf, size);
// Free the buffer
free(buf);
// Wait before sending the data again
delay(10);
}
Python Code:
#
# read struct from arduino / sample code below
#
import serial
import struct
# Open the serial port
ser = serial.Serial('/dev/ttyUSB0', 115200)
# The struct we expect to receive from the Arduino
#struct Data {
# int32_t value1;
# float value2;
# uint32_t value3;
#}
expFormat = "i f i i" # Format to match arduino struct
structDataLength = struct.calcsize(expFormat)
print(structDataLength) # RESULT IS 30
while True:
# Read the data from the serial port
# We read until we have received all the bytes for the struct
data = b''
while len(data) < structDataLength:
data += ser.read(structDataLength - len(data))
# Unpack the data into an instance of the Data struct
val = struct.unpack('i f i i', data)
# Print the values
print(val)
# Close the serial port
ser.close()