cstm32accelerometerspistm32cubemx

BMA253 Accelerometer Chip Id Receiving Error


I am interfacing the BMA253 Accelerometer with STM32 Discovery Board using 4 wire SPI. I am using the CUBEMX HAL Library. As a first step, I am trying to read the CHIP ID from the sensor register 0x00. The chip which should be read is 0xFA. The following code is added in the while loop just for the purpose of verification. As SPI is a active low protocol, I have configured PIN_2 to be high by default.

uint8_t result = 0;
uint8_t address = 0x00;
while (1)
{
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_2, GPIO_PIN_RESET);
HAL_SPI_Transmit(&hspi1, &address, 1, 100);
HAL_Delay (100);
HAL_SPI_Receive(&hspi1, &result, 1, 100);
HAL_Delay (100);
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_2, GPIO_PIN_SET);
}

Since it is in the infinite while loop, for the first two loop cycles I am getting 0xFF in the result. Then in the next two loop cycles, I am getting the correct Chip Id which is 0xFA. Then I am getting 0xFF in the next two loop cycles and this pattern is alternating infinitely.

I am not able to understand why I am receiving 0xFF first and then 0xFA.

Could there be a problem with the delay mismatch? I feel that 100ms should be fine.

I also feel that the SPI Receive is being incorrectly implemented. I am worrying because since SPI Read is an important function in retrieving the acceleration data, this function is the key.

I request anyone to please suggest me on what to do to get it working perfectly. Any help would be highly appreciated.

Thanks in advance.

EDIT: WORKING NOW 1. Followed theSealion's suggestion to set the first bit high. 2. Additionally, I had to configure the CPOL and CPHA in the SPI Configuration to either Mode 0 or Mode 3 as per the sensor requirement.


Solution

  • Please try the follwoing to ready the Chip ID

    #define READ_REGISTER 0x80
    uint8_t result = 0;
    uint8_t address = 0x00 + READ_REGISTER;
    
    while (1)
    {
        HAL_GPIO_WritePin(GPIOD, GPIO_PIN_2, GPIO_PIN_RESET);
        HAL_SPI_Transmit(&hspi1, &address, 1, 100);
        HAL_SPI_Receive(&hspi1, &result, 1, 100);
        HAL_GPIO_WritePin(GPIOD, GPIO_PIN_2, GPIO_PIN_SET);
    
        HAL_Delay (500);
    }
    

    According to the datasheet, if you want to read a register, the MSB of the command must be 1. And you do not need any within the communication.