Simvik

Car window motor: set the driver's register

Enable the motor and set its speed field without disturbing the register's other settings. An easy embedded C problem (Bit manipulation), run and graded in…

easy · Bit manipulation · masks · fields · read-modify-write · product

Product: Car window-lift motor driver (Automotive)

Requirement. The window-lift motor driver chip has one 8-bit control register:

BitsMeaning
7BRAKE: 1 holds the motor shorted
5–4SPEED: 0 (slowest) to 3 (fastest)
3ENABLE: 1 drives the motor
6, 2–0other settings (current limit, direction): never change them

Return the new register value from the current one. Always write the SPEED field (a speed above 3 means 3). When enabling, also clear BRAKE, or the driver fights its own brake. When disabling, clear only ENABLE.

Starter code

uint8_t motor_set(uint8_t reg, bool enable, uint8_t speed) {
  return enable ? (uint8_t)(1 << 3 | speed << 4) : 0;
}

Example tests

Enable at speed 2, then stop

printf("0x%02X 0x%02X\n", motor_set(0x00, true, 2), motor_set(0x28, false, 2));

Expected output:

0x28 0x20

The other settings survive

printf("0x%02X\n", motor_set(0x41, true, 1));

Expected output:

0x59

Learn it first

  • Bit manipulation · Masks, shifts, fields and the idioms every register access is built from.

More Bit manipulation problems