Hello.
I'm having issues reading magnetometer readings using SPI on a STM32. When using continuous mode 2, data shown is constant. I followed the reading procedure on the AK8963 datasheet. I initialized as follows:
- Power down mode
- wait
- Fuse mode
- Wait
- Read sensitivity adjustment values
- Power down
- Wait
- Go to continuous mode 2
It seems to work as the value 0x16 (the one I set) is always present when I read the CTL1 register.
When reading the magnetometer in the main loop, I follow this procedure: read status one -> check for ready bit -> if ready then read measurements + status 2 -> check status 2 for overflow -> if no overflow then save the measurement.
Here is the code for reading magnetometer:
/*** MAGNETOMETER ***/
uint8_t cmd = 0x80|reg, ready, magdata[7];
uint8_t data[14];
cmd = (MAG_STATUS_1|0x80);
HAL_GPIO_WritePin(SPI_CS_GPIO_Port, SPI_CS_Pin, GPIO_PIN_RESET);
HAL_SPI_Transmit(hspi, &cmd, 1, 100);
HAL_SPI_Receive(hspi, &ready, sizeof(ready), 100);
HAL_GPIO_WritePin(SPI_CS_GPIO_Port, SPI_CS_Pin, GPIO_PIN_SET);
if ((ready & 0x01) == 1) {
cmd = (MAG_DATA|0x80);
HAL_GPIO_WritePin(SPI_CS_GPIO_Port, SPI_CS_Pin, GPIO_PIN_RESET);
HAL_SPI_Transmit(hspi, &cmd, 1, 100);
HAL_SPI_Receive(hspi, magdata, sizeof(magdata), 100);
HAL_GPIO_WritePin(SPI_CS_GPIO_Port, SPI_CS_Pin, GPIO_PIN_SET);
uint8_t status = magdata[6];
if ((status & 0x8) == 0) {
imu->magneto.x = (float)(((int16_t)magdata[1]<<8) | magdata[0]);
imu->magneto.y = (float)(((int16_t)magdata[3]<<8) | magdata[2]);
imu->magneto.z = (float)(((int16_t)magdata[5]<<8) | magdata[4]);
}
}
the "imu" is a struct I made. It works fine when reading accelerometer and gyro data. Magnetometer readings are the same no matter the position in which I put the device: 42215.0; 5409.0; 6060.0.
Could anyone help me see my mistake?