2023-10-20 04:54 PM
The LIS3DSH accelerometer is located on the STM32F407VGT6.
I need to get the WHO_AM_I value from the LIS3DSH accelerometer register using CMSIS and SPI.
The SPI1->DR register is 8 bit.
I need to send the WHO_AM_I address and 8 more bits, a total of 16 bits should be sent.
I have an 8-bit SPI1->DR register, so I can’t send 16 bits at a time.
I think the algorithm of actions should be something like this:
SPI1->DR = data; //Here I send the register address WHO_AM_I
receive=SPI1->DR ; //Here I receive unnecessary data.
SPI1->DR = 0; //Here I send empty 8 bits
receive=SPI1->DR ; //Here I need to get the value of the WHO_AM_I register
I tried using this code (I wrote it myself), but it doesn't work:
uint8_t address=0x8F; //Register address+read
uint8_t result;
HAL_GPIO_WritePin(GPIOE, GPIO_PIN_3, GPIO_PIN_RESET); //Chip Select
SPI1->DR = address;
while((SPI1->SR & SPI_SR_BSY) != RESET);
result=SPI1->DR;
while((SPI1->SR & SPI_SR_BSY) != RESET);
SPI1->DR = 0;
while((SPI1->SR & SPI_SR_BSY) != RESET);
result=SPI1->DR;
while((SPI1->SR & SPI_SR_BSY) != RESET);
HAL_GPIO_WritePin(GPIOE, GPIO_PIN_3, GPIO_PIN_SET); //Chip Select
It is not possible to use the SPI_SR_TXE flag; the SPI_SR_TXE bit is always zero.
If I use the SPI_SR_TXE flag, then it takes the value zero after this line
SPI1->DR = address;
And after this, the SPI_SR_TXE flag does not receive the value 1.
Using HAL I get the correct data from the WHO_AM_I register
uint8_t address=0x8F; //Register address+read
uint8_t result;
HAL_GPIO_WritePin(GPIOE, GPIO_PIN_3, GPIO_PIN_RESET); //Chip Select
HAL_SPI_Transmit(&hspi1,&address,1,1000);
HAL_SPI_Receive(&hspi1,&result,1,1000);
HAL_GPIO_WritePin(GPIOE, GPIO_PIN_3, GPIO_PIN_SET); //Chip Select
This means that SPI is configured correctly and the accelerometer is working.
But I need to get the value of the WHO_AM_I register using CMSIS.
Solved! Go to Solution.
2023-10-20 04:57 PM
Did you set SPI_CR1_SPE?
2023-10-20 04:57 PM
Did you set SPI_CR1_SPE?
2023-10-20 05:51 PM - edited 2023-10-23 07:52 PM
SPI1->CR1 |= SPI_CR1_SPE;
uint8_t address=0x8F; //Register address+read
uint8_t result;
HAL_GPIO_WritePin(GPIOE, GPIO_PIN_3, GPIO_PIN_RESET); //Chip Select
while(!(SPI1->SR & SPI_SR_TXE));
SPI1->DR = address;
while(!(SPI1->SR & SPI_SR_TXE));
while(!(SPI1->SR & SPI_SR_RXNE));
result=SPI1->DR;
while((SPI1->SR & SPI_SR_RXNE));
while(!(SPI1->SR & SPI_SR_TXE));
SPI1->DR = 0;
while(!(SPI1->SR & SPI_SR_TXE));
while(!(SPI1->SR & SPI_SR_RXNE));
result=SPI1->DR;
while((SPI1->SR & SPI_SR_RXNE));
while((SPI1->SR & SPI_SR_BSY) != RESET);
HAL_GPIO_WritePin(GPIOE, GPIO_PIN_3, GPIO_PIN_SET); //Chip Select