Smartwatch: pixels for the display
Pack a 24-bit colour into the display's 16-bit RGB565 format, in the order SPI sends it. An easy embedded C problem (SPI), run and graded in the browser.
easy · SPI · rgb565 · packing · byte-order · product
Product: Smartwatch (Wearables)
Requirement. The watch face draws in 24-bit colour, but the display controller takes RGB565: 5 bits of red (the top bits), 6 of green, then 5 of blue, using the most significant bits of each 8-bit channel. Over SPI it expects the high byte first.
Fill out with the two bytes to send, out[0] first.
Starter code
void rgb565_be(uint8_t r, uint8_t g, uint8_t b, uint8_t out[2]) {
uint16_t v = (uint16_t)((r >> 3) | (g >> 2) << 5 | (b >> 3) << 11);
out[0] = (uint8_t)(v & 0xFF);
out[1] = (uint8_t)(v >> 8);
}Example tests
Red and white
uint8_t o[2];
rgb565_be(255, 0, 0, o);
printf("%02X %02X ", o[0], o[1]);
rgb565_be(255, 255, 255, o);
printf("%02X %02X\n", o[0], o[1]);Expected output:
F8 00 FF FFGreen and blue
uint8_t o[2];
rgb565_be(0, 255, 0, o);
printf("%02X %02X ", o[0], o[1]);
rgb565_be(0, 0, 255, o);
printf("%02X %02X\n", o[0], o[1]);Expected output:
07 E0 00 1FLearn it first
- SPI · Clock modes, chip select, multiple devices and throughput.
More SPI problems
- What an SPI mode means · Turn an SPI mode number into the clock's idle level and the edge that samples data.
- Split a flash write at page boundaries · Cut a write into Page Program commands that never cross a page.
- Feed a daisy chain · Send bytes to a chain of 74HC595s so each chip shows its own pattern.
- Read registers in a burst · Read several registers with one command, setting the read bit and skipping the command's reply.
- Driver: bring up SPI and read a sensor's ID · Configure an SPI master and its chip-select pin, then read one register from a sensor.
- Driver: read an accelerometer in one burst · Power a sensor up over SPI and read its three axes in one chip-select assertion.
- Fix: the sensor ignores its configuration · A register write releases chip select while the last byte is still being clocked out.