Building on P_B's answer to pack additional data types, I extended the python as follows. Of course, the receiving Arduino code needs to receive into the correct data type as well.
def StuffInt(txfer_obj, int_to_send, start_pos=0):
"""Insert integer into pySerialtxfer TX buffer starting at the specified index."""
return StuffObject(txfer_obj, int_to_send, 'i', 4, start_pos=0)
def StuffFloat(txfer_obj, float_to_send, start_pos=0):
"""Insert integer into pySerialtxfer TX buffer starting at the specified index."""
return StuffObject(txfer_obj, float_to_send, 'f', 4, start_pos=0)
def StuffStr(txfer_obj, string_to_send, max_length=None, start_pos=0):
"""Insert string into pySerialtxfer TX buffer starting at the specified index.
Args:
txfer_obj: see StuffObject
string_to_send: see StuffObject
max_length: if provided, the string is truncated to the requested size; otherwise
defaults to the length of the string
object_byte_size: integer number of bytes of the object to pack
start_pos: see StuffObject
Returns:
start_pos for next object
"""
if max_length is None:
max_length = len(string_to_send)
format_string = '%ds' % max_length
truncated_string = string_to_send[:max_length]
truncated_string_b = bytes(truncated_string, 'ascii')
print (truncated_string_b)
return StuffObject(txfer_obj, truncated_string_b, format_string, max_length, start_pos=0)
def StuffObject(txfer_obj, val, format_string, object_byte_size, start_pos=0):
"""Insert an object into pySerialtxfer TX buffer starting at the specified index.
Args:
txfer_obj: txfer - Transfer class instance to communicate over serial
val: value to be inserted into TX buffer
format_string: string used with struct.pack to pack the val
object_byte_size: integer number of bytes of the object to pack
start_pos: index of the last byte of the float in the TX buffer + 1
Returns:
start_pos for next object
"""
val_bytes = struct.pack(format_string, val)
for index in range(object_byte_size):
txfer_obj.txBuff[index + start_pos] = val_bytes[index]
return object_byte_size + start_pos