Drone: pack a telemetry packet
Serialise a telemetry struct into an exact 12-byte, high-byte-first packet for the radio. A medium embedded C problem (Structs, unions and memory layout),…
medium · Structs, unions and memory layout · serialisation · big-endian · padding · product
Product: Drone flight controller (Aerospace and drones)
Requirement. The drone sends telemetry to the ground station 50 times a second. The ground station runs on a different processor and compiler, so the packet layout is fixed by the protocol, not by the struct:
| Bytes | Field |
|---|---|
| 0–1 | seq |
| 2–5 | altitude_cm (signed) |
| 6–7 | roll_cd (signed) |
| 8–9 | pitch_cd (signed) |
| 10 | battery_pct |
| 11 | flags |
Every multi-byte field is sent high byte first. Fill out with the 12 bytes.
Starter code
void pack_telemetry(const telem_t *t, uint8_t out[12]) {
memcpy(out, t, 12);
}Example tests
In flight
telem_t t = { 0x0102, 1000, -150, 300, 87, 0x05 };
uint8_t o[12];
pack_telemetry(&t, o);
for (int i = 0; i < 12; i++) printf("%02X ", o[i]);
printf("\n");Expected output:
01 02 00 00 03 E8 FF 6A 01 2C 57 05Below the take-off point
telem_t t = { 65535, -250, 0, 0, 0, 0 };
uint8_t o[12];
pack_telemetry(&t, o);
for (int i = 0; i < 12; i++) printf("%02X ", o[i]);
printf("\n");Expected output:
FF FF FF FF FF 06 00 00 00 00 00 00Learn it first
- Structs, unions, alignment and byte order · Alignment and unaligned access, padding, packing, byte order, unions and bit-fields.
More Structs, unions and memory layout problems
- Remove the padding · Reorder struct members to shrink it from 12 bytes to 8.
- Pack a wire header · Declare a struct that matches a 7-byte protocol header exactly.
- Bits of a float · Return the IEEE 754 bit pattern of a float.
- Overlay a register with bit-fields · Describe an 8-bit control register with a union of a byte and bit-fields.
- Compare two structs · Test two structs for equality without being fooled by padding.
- Describe a tagged union · Format a message whose payload type depends on a tag.
- Return a struct by value · Compute the midpoint of two points and return it as a struct.
- Minimum and maximum of a log · Scan an array of structs and return two results through pointers.
- Serialise a struct · Write a struct to a byte buffer in a defined, portable format.
- Predict sizeof · Compute the size of a struct from the sizes of its members.
- Allocate a variable-length packet · Build a heap object with a flexible array member.
- Pack an RGB565 pixel · Squeeze 24-bit colour into the 16-bit format small displays use.
- Compare firmware versions · Order two semantic versions for an update check.
- Convert a header to host order · Fix up the multi-byte fields of a received big-endian header.
- Fix: old payload bytes leak into new packets · A packet is only partly cleared before it is reused.
- Fix: the receiver rejects every header · A header is serialised by copying a struct whose padding does not match the wire format.