HeapCrash / Challenges / Accelerometer readings make no sense

Accelerometer readings make no sense

A LIS3DH-style accelerometer at ±2 g in high-resolution mode: 12-bit two's complement, left-justified in little-endian register pairs starting at OUT_X_L (0x28), 1 mg per LSB. Multi-byte reads need the register address MSB set to auto-increment. Lying flat, Z should read about +1.0 g. Instead all three axes read the same value, and tilted the other way a small negative reading jumps to about +4 g.

The code

Embedded C for Cortex-M. It compiles. There are 3 real bugs in it: the kind that pass a bench test and fail in the field.

void accel_decode(const uint8_t raw[6], float g[3])
{
    for (int i = 0; i < 3; i++) {
        uint16_t v = (uint16_t)(raw[2 * i] << 8 | raw[2 * i + 1]);
        int16_t s = v >> 4;
        g[i] = s * 0.001f;
    }
}

bool accel_read(float g[3])
{
    uint8_t raw[6];
    if (HAL_I2C_Mem_Read(&hi2c1, ACC_ADDR << 1, OUT_X_L, I2C_MEMADD_SIZE_8BIT,
                         raw, 6, 10) != HAL_OK) return false;
    accel_decode(raw, g);
    return true;
}

What an interviewer expects

The bugs, reference fixes and the follow-up question are in the practice app, after you've tried it.

Companies that test this

Matched on the skills each company's embedded roles emphasise.

Related challenges

Flag the lines, say what breaks, then fix it and build it with clang in your browser.

Find the bugs