2024-06-29 11:34 PM
Context: I am trying to read the Chip ID from a BMP280 sensor using SPI communication with an STM32 microcontroller. The expected Chip ID value is 0x58. However, I am encountering inconsistent results when calling the function to read the Chip ID multiple times.
BMP280_Read_CHIP_ID();
BMP280_Read_CHIP_ID();
Problem: When I call the BMP280_Read_CHIP_ID function twice consecutively, I get the following outputs:
UART Output.
The first read returns 0x00 (unexpected), while the second read returns the correct Chip ID 0x58.
Code:
Here is the function I am using to read the Chip ID:
void BMP280_Read_CHIP_ID()
{
uint8_t data = 0;
uint8_t address = 0xD0;
address |= 0x80;
CS_Enable();
delay_ms(2);
SPI_Transmit(&address, 1);
delay_ms(2);
SPI_Receive(&data, 1);
delay_ms(2);
CS_Disable();
printf("Chip ID Read - %x\n\r", data);
}
SPI_Transmit Function:
void SPI_Transmit (uint8_t *data, int size)
{
int i=0;
while (i<size)
{
while (!((SPI1->SR)&(1<<1))) {};
SPI1->DR = data[i];
i++;
}
while (!((SPI1->SR)&(1<<1))) {};
while (((SPI1->SR)&(1<<7))) {};
// Clear the Overrun flag by reading DR and SR
uint8_t temp = SPI1->DR;
temp = SPI1->SR;
}
SPI_Receive Function:
void SPI_Receive (uint8_t *data, int size)
{
while (size)
{
while (((SPI1->SR)&(1<<7))) {};
SPI1->DR = 0; // send dummy data
while (!((SPI1->SR) &(1<<0))){};
*data++ = (SPI1->DR);
size--;
}
}