Review: the sensor's temperature is read in the wrong byte order
A driver copies a big-endian signed field straight into a little-endian int16t. A medium embedded C problem (Code review for embedded C), run and graded in…
medium · Code review for embedded C · find-the-bug · code-review · endianness · sign-extension
Review comment. "The sensor sends the temperature MSB first (bytes 2 and 3 of the frame, signed, in 1/256 °C). memcpy into an int16_t takes the host's byte order, which is little-endian on this MCU, so 25.0 °C reads as 0.25 °C. Build the value from the bytes explicitly."
Fix temp_centi by changing at most two lines. It returns hundredths of a degree; negative temperatures must work too.
Starter code
int16_t temp_centi(const uint8_t *frame) {
int16_t raw;
memcpy(&raw, &frame[2], 2);
return (int16_t)(raw * 100 / 256);
}Example tests
Room temperature
show(0x19, 0x00);
show(0x16, 0x80);Expected output:
19 00: 2500
16 80: 2250Learn it first
- Code review for embedded C · What to look for in firmware changes, how to comment, and what to leave to tools.
More Code review for embedded C problems
- Review: a length from the packet is trusted · A message decoder copies as many bytes as the packet says, into a fixed-size buffer.
- Review: an error path keeps the bus lock · After one failed sensor read, every later read on the shared bus deadlocks.
- Review: sizeof on an array parameter · A function meant to clear a receive buffer only clears its first few bytes.
- Review: a timeout that breaks after 49 days · A deadline check adds to a 32-bit millisecond tick, which wraps.
- Review: the ring buffer grew to 100 bytes · A change resized a ring buffer, but its index wrap still uses a bit mask.
- Review: blocks got bigger than the loop counter · A checksum loop uses a uint8_t index, and the block size was raised past 255.
- Review: strncpy does not always terminate · A setter copies a name with strncpy, and a long name leaves the field without a terminator.