Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bit shifting causing intermittent bit corruption #29

Open
sdhunna21 opened this issue Mar 9, 2023 · 1 comment
Open

Bit shifting causing intermittent bit corruption #29

sdhunna21 opened this issue Mar 9, 2023 · 1 comment

Comments

@sdhunna21
Copy link

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;
	```
@fleutot
Copy link

fleutot commented Jan 25, 2024

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;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants