#include <SPI.h>
#include <Wire.h>
#include <Arduino.h>
// MPU9250 + AK8963 相关定义
#define CS_PIN PC4
HardwareSerial Serial1(PA10, PA9); // USB to PC
HardwareSerial Serial2(PA3, PA2); // GPS Module
float gyro_bias[3] = {0};
float acc_bias[3] = {0};
float mag_adjust[3] = {1.0, 1.0, 1.0};
float mag_bias[3] = {10.0f, -20.0f, 5.0f}; // Example bias, calibrate for accuracy
float mag_scale[3] = {1.02f, 0.97f, 1.05f}; // Example scale, calibrate for accuracy
#define MPU_PWR_MGMT_1 0x6B
#define MPU_USER_CTRL 0x6A
#define MPU_I2C_MST_CTRL 0x24
#define MPU_I2C_SLV0_ADDR 0x25
#define MPU_I2C_SLV0_REG 0x26
#define MPU_I2C_SLV0_DO 0x63
#define MPU_I2C_SLV0_CTRL 0x27
#define MPU_EXT_SENS_DATA_00 0x49
unsigned long last_time = 0;
const unsigned long SAMPLE_PERIOD_MS = 10; // 100Hz采样周期
// MS5611 相关定义
#define MS5611_ADDR 0x77
#define CMD_RESET 0x1E
#define CMD_PROM_READ 0xA0
#define CMD_CONV_D1 0x48
#define CMD_CONV_D2 0x58
#define CMD_ADC_READ 0x00
uint16_t C[7]; // MS5611校准参数
TwoWire myI2C(PC9, PA8); // I2C3 SDA=PA8, SCL=PC9
// GPS UBX 相关定义
#define UBX_HEADER_1 0xB5
#define UBX_HEADER_2 0x62
#define MAX_PACKET_SIZE 1024 // Adjust based on maximum expected UBX message size (NAV-PVT is ~92 bytes + header/checksum)
uint8_t buf[MAX_PACKET_SIZE];
int bufIndex = 0;
int payloadLength = 0;
bool receiving = false;
struct NavPVT {
uint32_t iTOW;
uint16_t year;
uint8_t month, day, hour, min, sec, valid; // valid bitmask
int32_t lon; // degE7
int32_t lat; // degE7
int32_t height; // mm
uint8_t fixType;
// Removed bool updated;
} navpvt;
// Initialize navpvt with default/invalid values
void init_navpvt() {
navpvt.iTOW = 0;
navpvt.year = 0;
navpvt.month = 0; navpvt.day = 0; navpvt.hour = 0; navpvt.min = 0; navpvt.sec = 0;
navpvt.valid = 0;
navpvt.lon = 0;
navpvt.lat = 0;
navpvt.height = 0;
navpvt.fixType = 0; // 0: No fix
}
// --- MPU9250 SPI函数 ---
uint8_t SPI_ReadWrite(uint8_t data) {
// Add check if SPI is initialized, though SPI.begin() is in setup.
return SPI.transfer(data);
}
void MPU_Write(uint8_t reg, uint8_t val) {
digitalWrite(CS_PIN, LOW);
SPI_ReadWrite(reg & 0x7F); // Ensure write bit is not set
SPI_ReadWrite(val);
digitalWrite(CS_PIN, HIGH);
// delayMicroseconds(10); // Original code used this, might be needed depending on chip/bus speed
}
uint8_t MPU_Read(uint8_t reg) {
digitalWrite(CS_PIN, LOW);
SPI_ReadWrite(reg | 0x80); // Set read bit
uint8_t val = SPI_ReadWrite(0xFF); // Send dummy byte to receive data
digitalWrite(CS_PIN, HIGH);
// delayMicroseconds(10); // Original code used this
return val;
}
void MPU_Read_Multi(uint8_t reg, uint8_t *buf, uint8_t len) {
digitalWrite(CS_PIN, LOW);
SPI_ReadWrite(reg | 0x80); // Set read bit
for (uint8_t i = 0; i < len; i++)
buf[i] = SPI_ReadWrite(0xFF); // Send dummy byte for each byte received
digitalWrite(CS_PIN, HIGH);
// delayMicroseconds(10); // Original code used this
}
// Functions for interfacing with AK8963 via MPU9250's I2C Master
void AK8963_ReadBytes(uint8_t ak_reg, uint8_t len) {
// Configure MPU9250 I2C Master to read from AK8963
MPU_Write(MPU_I2C_SLV0_ADDR, 0x8C); // AK8963 I2C address 0x0C, Read bit 0x80
MPU_Write(MPU_I2C_SLV0_REG, ak_reg); // AK8963 register to read from
MPU_Write(MPU_I2C_SLV0_CTRL, 0x80 | len); // Enable I2C and specify number of bytes to read
// Data will be available in MPU_EXT_SENS_DATA registers after this.
delayMicroseconds(100); // Wait for I2C transaction to complete
}
void AK8963_WriteByte(uint8_t reg, uint8_t val) {
// Configure MPU9250 I2C Master to write to AK8963
MPU_Write(MPU_I2C_SLV0_ADDR, 0x0C); // AK8963 I2C address 0x0C, Write bit 0x00
MPU_Write(MPU_I2C_SLV0_REG, reg); // AK8963 register to write to
MPU_Write(MPU_I2C_SLV0_DO, val); // Data to write
MPU_Write(MPU_I2C_SLV0_CTRL, 0x81); // Enable I2C and specify 1 byte to write
delay(10); // Wait for I2C transaction to complete
}
void init_ak8963() {
// Reset MPU9250 (optional, done in setup, but good practice)
MPU_Write(MPU_PWR_MGMT_1, 0x80); // Reset device
delay(100);
MPU_Write(MPU_PWR_MGMT_1, 0x00); // Wake up
// Enable MPU9250 I2C master mode
MPU_Write(MPU_USER_CTRL, 0x20); // Enable I2C Master mode
MPU_Write(MPU_I2C_MST_CTRL, 0x0D); // Set I2C clock speed (400kHz)
// Get AK8963 Calibration data (ASA)
AK8963_WriteByte(0x0A, 0x0F); // Enter fuse access mode
AK8963_ReadBytes(0x10, 3); // Read ASA registers (0x10-0x12)
delay(10); // Wait for data to be ready in MPU's external sensor buffer
uint8_t asa[3];
MPU_Read_Multi(MPU_EXT_SENS_DATA_00, asa, 3);
for (int i = 0; i < 3; i++)
mag_adjust[i] = ((asa[i] - 128) / 256.0f) + 1.0f; // Calculate adjust factors
// Configure AK8963 for continuous measurement mode 2 (100Hz)
AK8963_WriteByte(0x0A, 0x16); // Set continuous measurement mode 2 (100Hz, 16-bit)
}
bool read_ak8963(float *mag) {
// Request read from AK8963 (status, 6 data bytes, status)
AK8963_ReadBytes(0x02, 7); // Read ST1 (0x02), HXL-HZH (0x03-0x08), ST2 (0x09)
delayMicroseconds(160); // Wait for the transaction (approx 100Hz cycle time or slightly more)
uint8_t raw[7];
MPU_Read_Multi(MPU_EXT_SENS_DATA_00, raw, 7); // Read data from MPU's buffer
// Check Data Ready (ST1) and Overflow/Error (ST2) flags
// raw[0] is ST1, raw[6] is ST2
if (raw[0] & 0x01) { // Check Data Ready (DRDY bit in ST1)
if (!(raw[6] & 0x08)) { // Check Magnetic sensor overflow (HOFL bit in ST2)
int16_t mx = (raw[2] << 8) | raw[1]; // Data is Little Endian
int16_t my = (raw[4] << 8) | raw[3];
int16_t mz = (raw[6] << 8) | raw[5]; // ST2 is at index 6, need to be careful with this read order. Let's re-check the read bytes. AK8963_ReadBytes(0x03, 7) means read from 0x03 for 7 bytes: HXL, HXH, HYL, HYH, HZL, HZH, ST2. ST1 is at 0x02 and is usually read first to check DRDY. Let's correct the read bytes.
// --- Correction: Read ST1 first to check data ready ---
// AK8963_ReadBytes(0x02, 1); // Read ST1
// delayMicroseconds(100);
// uint8_t st1 = MPU_Read(MPU_EXT_SENS_DATA_00);
// if (!(st1 & 0x01)) return false; // Data not ready
// AK8963_ReadBytes(0x03, 7); // Read HXL to ST2
// delayMicroseconds(160); // Wait for transaction
// MPU_Read_Multi(MPU_EXT_SENS_DATA_00, raw, 7);
// Reverting to original read_ak8963 as it reads all 7 bytes starting from 0x03,
// but assumes ST1 check might be handled differently or is less critical
// for 100Hz mode where DRDY is often ready. Let's fix the raw index mapping.
// raw[0]=HXL, raw[1]=HXH, raw[2]=HYL, raw[3]=HYH, raw[4]=HZL, raw[5]=HZH, raw[6]=ST2
mx = (raw[1] << 8) | raw[0]; // Corrected: HXL is raw[0], HXH is raw[1]
my = (raw[3] << 8) | raw[2];
mz = (raw[5] << 8) | raw[4];
if (!(raw[6] & 0x08)) { // Check Magnetic sensor overflow (HOFL bit in ST2)
float m_raw[3];
// Sensitivity adjust and conversion from raw to uT (microTesla)
// 16-bit mode sensitivity is 0.15 uT/LSB
m_raw[0] = mx * mag_adjust[0] * 0.15f;
m_raw[1] = my * mag_adjust[1] * 0.15f;
m_raw[2] = mz * mag_adjust[2] * 0.15f;
// Apply bias and scale compensation
for (int i = 0; i < 3; i++)
mag[i] = (m_raw[i] - mag_bias[i]) * mag_scale[i];
return true; // Data read and processed successfully
}
}
}
return false; // Data not ready or overflow occurred
}
// Corrected MPU9250_Write_Reg and MPU9250_Read_Reg to use correct SPI access pattern
void MPU9250_Write_Reg(uint8_t reg, uint8_t value) {
digitalWrite(CS_PIN, LOW);
SPI_ReadWrite(reg); // Address without read bit
SPI_ReadWrite(value);
digitalWrite(CS_PIN, HIGH);
delayMicroseconds(10); // Shorter delay might be sufficient
}
uint8_t MPU9250_Read_Reg(uint8_t reg) {
digitalWrite(CS_PIN, LOW);
SPI_ReadWrite(reg | 0x80); // Address with read bit
uint8_t val = SPI_ReadWrite(0xFF); // Dummy byte
digitalWrite(CS_PIN, HIGH);
delayMicroseconds(10); // Shorter delay might be sufficient
return val;
}
void MPU9250_Read_Multi(uint8_t reg, uint8_t *buffer, uint8_t len) {
digitalWrite(CS_PIN, LOW);
SPI_ReadWrite(reg | 0x80); // Address with read bit
for (uint8_t i = 0; i < len; i++) {
buffer[i] = SPI_ReadWrite(0xFF); // Dummy byte
}
digitalWrite(CS_PIN, HIGH);
delayMicroseconds(10); // Shorter delay might be sufficient
}
// --- Calibration functions ---
// Note: Accel/Gyro calibration should ideally be done before reading mag adjust
// since power management affects AK8963 access setup.
void calibrate_gyro() {
// Ensure MPU is awake and not in low power mode for calibration
MPU9250_Write_Reg(MPU_PWR_MGMT_1, 0x00); // Wake up
delay(100);
const int samples = 200;
int32_t sum[3] = {0};
Serial1.println("Calibrating Gyroscope (keep device still)...");
for (int i = 0; i < samples; i++) {
uint8_t buf[14]; // Read full sensor data block (Acc, Temp, Gyro)
MPU9250_Read_Multi(0x3B, buf, 14);
// Gyro data starts at index 8
int16_t gx = (buf[8] << 8) | buf[9];
int16_t gy = (buf[10] << 8) | buf[11];
int16_t gz = (buf[12] << 8) | buf[13];
sum[0] += gx;
sum[1] += gy;
sum[2] += gz;
delay(5); // Short delay between samples
}
// Calculate bias in dps (degrees per second)
// Assuming default gyro scale (FS_SEL=0) is +/- 250 deg/s -> 131 LSB/deg/s
// Assuming FS_SEL=1 (+/- 500 deg/s) as set later -> 65.5 LSB/deg/s
gyro_bias[0] = (sum[0] / (float)samples) / 65.5f;
gyro_bias[1] = (sum[1] / (float)samples) / 65.5f;
gyro_bias[2] = (sum[2] / (float)samples) / 65.5f;
Serial1.println("Gyroscope calibration done.");
Serial1.print("Gyro bias (dps): "); Serial1.print(gyro_bias[0], 3); Serial1.print(", ");
Serial1.print(gyro_bias[1], 3); Serial1.print(", "); Serial1.println(gyro_bias[2], 3);
}
void calibrate_acc() {
// Ensure MPU is awake
MPU9250_Write_Reg(MPU_PWR_MGMT_1, 0x00); // Wake up
delay(100);
const int samples = 500;
int32_t sum[3] = {0};
Serial1.println("Keep device still and flat during accelerometer calibration...");
for (int i = 0; i < samples; i++) {
uint8_t buf[14]; // Read full sensor data block
MPU9250_Read_Multi(0x3B, buf, 14);
// Accel data starts at index 0
int16_t ax = (buf[0] << 8) | buf[1];
int16_t ay = (buf[2] << 8) | buf[3];
int16_t az = (buf[4] << 8) | buf[5];
sum[0] += ax;
sum[1] += ay;
sum[2] += az;
delay(5); // Short delay between samples
}
// Calculate bias in raw counts
// Assuming default accel scale (AFS_SEL=0) is +/- 2g -> 16384 LSB/g
// Assuming AFS_SEL=1 (+/- 4g) as set later -> 8192 LSB/g
// We expect Z axis to read ~8192 (1g) when flat
acc_bias[0] = (float)sum[0] / samples;
acc_bias[1] = (float)sum[1] / samples;
acc_bias[2] = (float)sum[2] / samples - 8192.0f; // Subtract 1g equivalent
Serial1.println("Accelerometer calibration done.");
Serial1.print("Accelerometer bias (raw LSB): ");
Serial1.print(acc_bias[0], 2); Serial1.print(", ");
Serial1.print(acc_bias[1], 2); Serial1.print(", ");
Serial1.println(acc_bias[2], 2);
}
// --- MS5611 Functions ---
void resetSensor() {
myI2C.beginTransmission(MS5611_ADDR);
myI2C.write(CMD_RESET);
myI2C.endTransmission();
delay(3); // MS5611 requires > 2.8ms after reset
}
void readPROM() {
// C0 is not used (factory data), C1-C6 are calibration parameters
for (int i = 0; i < 7; i++) { // Loop from i=0 to 6, accessing C[0] to C[6]
uint8_t addr = CMD_PROM_READ + i * 2; // Addresses are 0xA0, 0xA2, ..., 0xAE
myI2C.beginTransmission(MS5611_ADDR);
myI2C.write(addr);
myI2C.endTransmission();
myI2C.requestFrom(MS5611_ADDR, 2);
if (myI2C.available() == 2) {
C[i] = ((uint16_t)myI2C.read() << 8) | myI2C.read();
} else {
// Handle error if PROM read fails
Serial1.println("MS5611 PROM read error!");
C[i] = 0; // Default to 0 on error
}
}
}
uint32_t readADC(uint8_t cmd) {
myI2C.beginTransmission(MS5611_ADDR);
myI2C.write(cmd); // Send conversion command (D1 for pressure, D2 for temperature)
myI2C.endTransmission();
delay(10); // Wait for conversion to complete (adjust based on OSR, 10ms is for OSR=4096)
myI2C.beginTransmission(MS5611_ADDR);
myI2C.write(CMD_ADC_READ); // Send ADC read command
myI2C.endTransmission();
myI2C.requestFrom(MS5611_ADDR, 3); // Request 3 bytes (24-bit result)
uint32_t val = 0;
if (myI2C.available() == 3) {
val = ((uint32_t)myI2C.read() << 16) | ((uint32_t)myI2C.read() << 8) | myI2C.read();
} else {
// Handle error if ADC read fails
Serial1.println("MS5611 ADC read error!");
val = 0; // Default to 0 on error
}
return val;
}
// --- GPS UBX Functions ---
void calcChecksum(const uint8_t *data, int len, uint8_t &ckA, uint8_t &ckB) {
ckA = 0;
ckB = 0;
for (int i = 0; i < len; i++) {
ckA = ckA + data[i];
ckB = ckB + ckA;
}
}
void parseNavPVT(const uint8_t *payload) {
// Populate the global navpvt struct
navpvt.iTOW = (uint32_t)payload[0] | ((uint32_t)payload[1] << 8) | ((uint32_t)payload[2] << 16) | ((uint32_t)payload[3] << 24);
navpvt.year = payload[4] | (payload[5] << 8);
navpvt.month = payload[6];
navpvt.day = payload[7];
navpvt.hour = payload[8];
navpvt.min = payload[9];
navpvt.sec = payload[10];
navpvt.valid = payload[11]; // bitfield: 0=Date Valid, 1=Time Valid, 2=Fully Resolved, 3=Mag Decl. Valid, 7=GNSS Fix Ok
navpvt.fixType = payload[20]; // 0=No Fix, 1=Dead Reckoning, 2=2D, 3=3D, 4=GNSS+DR, 5=Time only fix
// Location data (Lat/Lon/Height are Int32, mm or degE7)
// Ensure correct byte ordering and casting
navpvt.lon = (int32_t)(payload[24] | ((int32_t)payload[25] << 8) | ((int32_t)payload[26] << 16) | ((int32_t)payload[27] << 24));
navpvt.lat = (int32_t)(payload[28] | ((int32_t)payload[29] << 8) | ((int32_t)payload[30] << 16) | ((int32_t)payload[31] << 24));
navpvt.height = (int32_t)(payload[32] | ((int32_t)payload[33] << 8) | ((int32_t)payload[34] << 16) | ((int32_t)payload[35] << 24)); // Height above Ellipsoid in mm
// Velocity data (optional, but part of NAV-PVT)
// int32_t velN = (int32_t)(payload[36] | ((int32_t)payload[37] << 8) | ((int32_t)payload[38] << 16) | ((int32_t)payload[39] << 24)); // NED North velocity, mm/s
// int32_t velE = (int32_t)(payload[40] | ((int32_t)payload[41] << 8) | ((int32_t)payload[42] << 16) | ((int32_t)payload[43] << 24)); // NED East velocity, mm/s
// int32_t velD = (int32_t)(payload[44] | ((int32_t)payload[45] << 8) | ((int32_t)payload[46] << 16) | ((int32_t)payload[47] << 24)); // NED Down velocity, mm/s
// int32_t gSpeed = (int32_t)(payload[48] | ((int32_t)payload[49] << 8) | ((int32_t)payload[50] << 16) | ((int32_t)payload[51] << 24)); // Ground Speed, mm/s
// int32_t heading = (int32_t)(payload[52] | ((int32_t)payload[53] << 8) | ((int32_t)payload[54] << 16) | ((int32_t)payload[55] << 24)); // Heading of motion (2D), degE5
// Accuracy estimates (optional)
// uint32_t hAcc = (uint32_t)(payload[40] | ((uint32_t)payload[41] << 8) | ((uint32_t)payload[42] << 16) | ((uint32_t)payload[43] << 24)); // Horizontal Accuracy Estimate, mm
// uint32_t vAcc = (uint32_t)(payload[44] | ((uint32_t)payload[45] << 8) | ((uint32_t)payload[46] << 16) | ((uint32_t)payload[47] << 24)); // Vertical Accuracy Estimate, mm
// The global 'navpvt' struct is now updated with the latest data.
// We don't set a 'updated' flag anymore, as the 100Hz loop will always read the current state.
}
void processGPS() {
while (Serial2.available()) {
uint8_t c = Serial2.read();
if (!receiving) {
if (c == UBX_HEADER_1) {
bufIndex = 0;
buf[bufIndex++] = c;
receiving = true;
}
} else if (bufIndex == 1) {
if (c == UBX_HEADER_2) {
buf[bufIndex++] = c;
} else {
// If second header byte is wrong, reset
receiving = false;
bufIndex = 0;
}
} else if (bufIndex < 6) { // Reading Class, ID, Length (4 bytes)
buf[bufIndex++] = c;
if (bufIndex == 6) {
// Length is Little Endian
payloadLength = buf[4] | (buf[5] << 8);
// Basic check to prevent buffer overflow or unreasonable length
if (payloadLength > MAX_PACKET_SIZE - 8 || payloadLength < 0) { // 8 = header + checksum
Serial1.print("GPS: Invalid payload length received: "); Serial1.println(payloadLength);
receiving = false;
bufIndex = 0;
continue;
}
// If length is 0, it's just header + checksum
if (payloadLength == 0) {
// Process checksum for 0-length payload if needed, then reset
receiving = false;
bufIndex = 0;
// For NAV-PVT, payloadLength is ~92, so 0 length is unexpected
continue;
}
}
} else { // Reading Payload and Checksum
if (bufIndex < MAX_PACKET_SIZE) { // Check buffer bounds before writing
buf[bufIndex++] = c;
} else {
// Buffer overflow, reset
Serial1.println("GPS: Buffer overflow");
receiving = false;
bufIndex = 0;
continue;
}
if (bufIndex >= 6 + payloadLength + 2) { // 6 header bytes + payload + 2 checksum bytes
// Packet complete
receiving = false;
uint8_t receivedCkA = buf[bufIndex - 2];
uint8_t receivedCkB = buf[bufIndex - 1];
uint8_t calculatedCkA, calculatedCkB;
// Checksum is calculated over message class, ID, and payload (bytes from index 2 up to payload end)
calcChecksum(buf + 2, 4 + payloadLength, calculatedCkA, calculatedCkB);
if (receivedCkA == calculatedCkA && receivedCkB == calculatedCkB) {
uint8_t msgClass = buf[2];
uint8_t msgId = buf[3];
// Check if it's a NAV-PVT message (Class: 0x01, ID: 0x07)
if (msgClass == 0x01 && msgId == 0x07) {
parseNavPVT(buf + 6); // Pass payload starting after header
// --- Modification: No need to set update flag here ---
// The main loop will read the latest navpvt state directly
} else {
// Optional: print other received UBX message types for debugging
// Serial1.print("GPS: Received UBX message Class 0x"); Serial1.print(msgClass, HEX);
// Serial1.print(", ID 0x"); Serial1.println(msgId, HEX);
}
} else {
// Checksum error
Serial1.print("GPS: Checksum error. Calculated: "); Serial1.print(calculatedCkA, HEX); Serial1.print(","); Serial1.print(calculatedCkB, HEX);
Serial1.print(" Received: "); Serial1.print(receivedCkA, HEX); Serial1.print(","); Serial1.println(receivedCkB, HEX);
}
bufIndex = 0; // Reset buffer index for the next packet
}
}
}
}
void setup() {
// Configure CS pin for SPI
pinMode(CS_PIN, OUTPUT);
digitalWrite(CS_PIN, HIGH); // Deselect MPU9250 initially
// Initialize SPI peripheral (SPI1 on STM32)
// SPI.begin() typically uses default pins (PA4-NSS, PA5-SCK, PA6-MISO, PA7-MOSI for SPI1 on some boards like Bluepill)
// If your board/variant uses different defaults or a different SPI instance (SPI2, SPI3),
// you might need to specify pins or use SPI.begin(SCK, MISO, MOS, SS).
SPI.begin();
SPI.setClockDivider(SPI_CLOCK_DIV16); // Set SPI clock (e.g., 84MHz/16 = 5.25MHz for APB2 clock)
SPI.setBitOrder(MSBFIRST);
SPI.setDataMode(SPI_MODE0); // CPOL=0, CPHA=0
// Initialize Serial ports
Serial1.begin(115200); // USB to PC
Serial2.begin(115200); // GPS Module
delay(100); // Give serials time to initialize
Serial1.println("Integrated IMU+Barometer+GPS System Started");
// Initialize I2C peripheral (I2C3 on STM32)
myI2C.begin(); // Configured with PC9 (SCL), PA8 (SDA) as per definition
// Initialize MS5611
resetSensor();
readPROM();
Serial1.println("MS5611 PROM Parameters:");
// C[0] is factory data, C[1] to C[6] are calibration coefficients
for (int i = 1; i <= 6; i++) {
Serial1.print("C"); Serial1.print(i); Serial1.print(" = ");
Serial1.println(C[i]);
}
// Initialize MPU9250 and AK8963
// MPU9250 setup
MPU9250_Write_Reg(MPU_PWR_MGMT_1, 0x00); // Exit sleep mode
delay(100);
// Set Gyroscope Full Scale Range
// 0x00 = +/- 250 deg/s
// 0x08 = +/- 500 deg/s
// 0x10 = +/- 1000 deg/s
// 0x18 = +/- 2000 deg/s
MPU9250_Write_Reg(0x1B, 0x08); // Gyroscope Full Scale: +/- 500 dps (FS_SEL=1)
// Set Accelerometer Full Scale Range
// 0x00 = +/- 2g
// 0x08 = +/- 4g
// 0x10 = +/- 8g
// 0x18 = +/- 16g
MPU9250_Write_Reg(0x1C, 0x08); // Accelerometer Full Scale: +/- 4g (AFS_SEL=1)
delay(10); // Allow settings to take effect
init_ak8963(); // Initialize AK8963 and read calibration data
// Perform calibrations
// Note: It's generally better to calibrate accel/gyro after setting scale and waking up MPU
calibrate_gyro();
calibrate_acc();
// Initialize GPS data structure with invalid values
init_navpvt();
Serial1.println("CSV Header: Time(ms),AccX(g),AccY(g),AccZ(g),GyroX(dps),GyroY(dps),GyroZ(dps),MagX(uT),MagY(uT),MagZ(uT),Pressure(hPa),Temp(C),Lat(deg),Lon(deg),Height(m),FixType");
}
void loop() {
// Process GPS data (non-blocking). This function updates the global navpvt struct
// whenever new data is received.
processGPS();
// Check if it's time for the next sensor reading and output
unsigned long now = millis();
if (now - last_time >= SAMPLE_PERIOD_MS) {
last_time = now;
// Read MPU9250 Accelerometer and Gyroscope data
uint8_t mpu_buf[14]; // Reads ACCEL_XOUT_H to GYRO_ZOUT_L
MPU9250_Read_Multi(0x3B, mpu_buf, 14);
// Raw accelerometer data (AFS_SEL=1 -> +/-4g -> 8192 LSB/g)
int16_t ax_raw = (mpu_buf[0] << 8) | mpu_buf[1];
int16_t ay_raw = (mpu_buf[2] << 8) | mpu_buf[3];
int16_t az_raw = (mpu_buf[4] << 8) | mpu_buf[5];
// Raw temperature data
int16_t temp_raw = (mpu_buf[6] << 8) | mpu_buf[7];
// Raw gyroscope data (FS_SEL=1 -> +/-500 dps -> 65.5 LSB/dps)
int16_t gx_raw = (mpu_buf[8] << 8) | mpu_buf[9];
int16_t gy_raw = (mpu_buf[10] << 8) | mpu_buf[11];
int16_t gz_raw = (mpu_buf[12] << 8) | mpu_buf[13];
// Apply accelerometer bias and scale (convert to g)
float acc[3] = {
((ax_raw - acc_bias[0]) / 8192.0f), // Converted to g
((ay_raw - acc_bias[1]) / 8192.0f),
((az_raw - acc_bias[2]) / 8192.0f)
};
// Convert temperature to degrees C
float temp_C = (temp_raw / 340.0f) + 21.0f; // MPU9250 temp formula
// Apply gyroscope bias and scale (convert to dps)
float gyro[3] = {
(gx_raw / 65.5f) - gyro_bias[0], // Converted to dps
(gy_raw / 65.5f) - gyro_bias[1],
(gz_raw / 65.5f) - gyro_bias[2]
};
// Read AK8963 Magnetometer data
float mag[3] = {0, 0, 0}; // Initialize to zero in case read fails
read_ak8963(mag); // This function applies adjust, bias, and scale internally
// Read MS5611 Temperature and Pressure
uint32_t D1 = readADC(CMD_CONV_D1); // Digital Pressure
uint32_t D2 = readADC(CMD_CONV_D2); // Digital Temperature
// MS5611 temperature and pressure compensation calculations (Datasheet equations)
// Using 64-bit integers for intermediate calculations to prevent overflow
int64_t dT = D2 - ((int64_t)C[5] << 8);
int64_t TEMP = 2000 + ((dT * C[6]) >> 23); // Actual Temperature (* 100)
int66_t OFF = ((int64_t)C[2] << 16) + ((C[4] * dT) >> 7); // Offset (* 1)
int66_t SENS = ((int64_t)C[1] << 15) + ((C[3] * dT) >> 8); // Sensitivity (* 1)
// Second order compensation for temperature effects (optional but improves accuracy)
// Check datasheet for specific conditions for second order compensation
if (TEMP < 2000) { // If temperature is below 20 C
int64_t T2 = (dT * dT) >> 31;
int64_t Off2 = (5 * (TEMP - 2000) * (TEMP - 2000)) >> 1;
int64_t Sens2 = (5 * (TEMP - 2000) * (TEMP - 2000)) >> 2;
if (TEMP < -1500) { // If temperature is below -15 C
Off2 += (15 * (TEMP + 1500) * (TEMP + 1500));
Sens2 += (8 * (TEMP + 1500) * (TEMP + 1500));
}
TEMP = TEMP - T2;
OFF = OFF - Off2;
SENS = SENS - Sens2;
}
int32_t P = (((D1 * SENS) >> 21) - OFF) >> 15; // Pressure (* 1) Pascal
// Output data in CSV format: Time(ms),AccX,AccY,AccZ,GyroX,GyroY,GyroZ,MagX,MagY,MagZ,Pressure,Temp(MS),Lat,Lon,Height,FixType
Serial1.print(now); Serial1.print(",");
Serial1.print(acc[0], 6); Serial1.print(",");
Serial1.print(acc[1], 6); Serial1.print(",");
Serial1.print(acc[2], 6); Serial1.print(",");
Serial1.print(gyro[0], 6); Serial1.print(",");
Serial1.print(gyro[1], 6); Serial1.print(",");
Serial1.print(gyro[2], 6); Serial1.print(",");
Serial1.print(mag[0], 3); Serial1.print(",");
Serial1.print(mag[1], 3); Serial1.print(",");
Serial1.print(mag[2], 3); Serial1.print(",");
Serial1.print(P / 100.0f, 2); Serial1.print(","); // Pressure in hPa
Serial1.print(TEMP / 100.0f, 2); Serial1.print(","); // MS5611 Temp in C
// GPS data - Always print the current state of the navpvt struct
// The processGPS() function keeps this struct updated as new data arrives
Serial1.print(navpvt.lat / 1e7, 7); Serial1.print(","); // Lat in degrees
Serial1.print(navpvt.lon / 1e7, 7); Serial1.print(","); // Lon in degrees
Serial1.print(navpvt.height / 1000.0, 3); Serial1.print(","); // Height in meters
Serial1.println(navpvt.fixType); // GPS Fix Type (integer code)
}
}