cancel
Showing results for 
Search instead for 
Did you mean: 

Pointed value from function reads out 0 on STM32, but on PC works fine

maharramov
Associate II

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.

4 REPLIES 4

Look at the code generated by the compiler

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
Pavel A.
Evangelist III

> Decided to test the function with the following code, it didn't work either:

> Commented line prints the correct value though.

So: it actually works. Now hook your logic analyzer to the SPI and debug the real SPI communication.

--pa

Warning, I am an amateur programmer. I've never done anything like this before, so maybe now is the time. I'm going to see if I can figure it out.

Yes, for sure. If I wrote the function to return the value, then it would return the expected value. But I'd like to write the result to a pointer variable.