0

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.

TECHKEY
  • 95
  • 1
  • 5

1 Answers1

1

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.

theSealion
  • 1,082
  • 7
  • 13
  • Thank you very much for your suggestion. I just implemented the same what you recommend. Now, the toggling of the value in result has been stopped. But it is just showing 0xFF instead of 0xFA. Can you please suggest some inputs? – TECHKEY Mar 25 '20 at 08:49
  • 1
    Could you please add a check of the results form the HAL_SPI_ calls. And (since you have a scope) have a look at the bus and add a picture from the communication? – theSealion Mar 25 '20 at 09:07
  • You're correct! I added the READ_REGISTER bit. Additionally, I had to configure the CPOL and CPHA based on the sensor, to get it working. Thanks theSealion – TECHKEY Apr 02 '20 at 10:01