Pointed value from function reads out 0 on STM32, but on PC works fine
Hello everyone,
I am trying to communicate with an accelerometer. But for some reason can't get the SPI read function to work.
Originally I wrote the following code to read the temperature, it did not work:
uint8_t CMS300_read(uint32_t addr, uint32_t *data)
{
addr |= cmsCRC(addr);
uint8_t *p = (uint8_t*) &addr
uint8_t txBuf[4] = { p[3], p[2], p[1], p[0] };
uint8_t rxBuf[4];
HAL_GPIO_WritePin(SPI1_SEL_GPIO_Port, SPI1_SEL_Pin, GPIO_PIN_RESET);
uint8_t status = (HAL_SPI_TransmitReceive(&hspi1, txBuf, rxBuf, 4, HAL_MAX_DELAY) == HAL_OK);
HAL_GPIO_WritePin(SPI1_SEL_GPIO_Port, SPI1_SEL_Pin, GPIO_PIN_SET);
*data = rxBuf[3] | (rxBuf[2] << 8) | (rxBuf[1] << 16) | (rxBuf[0] << 24);
return status;
}
int main(void)
{
while (1)
{
uint32_t data;
CMS300_read(REQ_READ_TEMP, &data);
printf("Result: 0x%08X\r\n", data);
HAL_Delay(1000);
}
}Basically the "data" reads out a 0.
Decided to test the function with the following code, it didn't work either:
uint8_t CMS300_read(uint32_t addr, uint32_t *data)
{
uint8_t *p = (uint8_t *)&addr;
uint8_t rxBuf[4] = {p[3], p[2], p[1], p[0]};
*data = rxBuf[3] | (rxBuf[2] << 8) | (rxBuf[1] << 16) | (rxBuf[0] << 24);
// printf("Result: 0x%08X\r\n", rxBuf[3] | (rxBuf[2] << 8) | (rxBuf[1] << 16) | (rxBuf[0] << 24));
}Commented line prints the correct value though.
But then I tested the code on PC, it works without problem and gives an expected result:
#include <stdio.h>
#include <stdint.h>
#define REQ_READ_TEMP ((1ULL << 15) | (1ULL << 13) | (1ULL << 9) | (1ULL << 8))
uint8_t CMS300_read(uint32_t addr, uint32_t *data)
{
uint8_t *p = (uint8_t *)&addr;
uint8_t rxBuf[4] = {p[3], p[2], p[1], p[0]};
*data = rxBuf[3] | (rxBuf[2] << 8) | (rxBuf[1] << 16) | (rxBuf[0] << 24);
}
int main()
{
uint32_t data;
CMS300_read(REQ_READ_TEMP, &data);
printf("Result: 0x%08X\r\n", data);
return 0;
}Can anyone tell why the code does not work on STM32?
Thanks.
