analogdevicesinc / TMC-API

TRINAMIC's IC API

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Bit shifting causing intermittent bit corruption

sdhunna21 opened this issue · comments

https://github.com/trinamic/TMC-API/blob/3da0cec86d2f14c3f1b6f29950df6fe2cc41624b/tmc/ic/TMC5160/TMC5160.c#L53

Sometimes when reading a spi value the upper 16 bits are all 1's. I noticed this line of code and changed it like so and the problem was resolved.

Shifting bits with types smaller than the shift can cause undefined behavour. At least on our processor, the msp430 it needs this fix.

	uint32_t v[5] = {0};
	for (uint32_t i = 0; i < 5; i++) {
		v[i] = data[i];
	}

	uint32_t value = (v[1] << 24) | (v[2] << 16) | (v[3] << 8) | (v[4]);
	return value;
	```

Good catch!

You could also skip the uint32_t array, and the hard-coded shift sizes (untested):

uint32_t value = 0;
for (int i = 5 - 1; i >= 1; i--) {
    value <<= 8;
    value |= data[i];
}
return value;