AVR-Playground/MPU6050.c

70 lines
2.3 KiB
C
Raw Permalink Normal View History

2024-03-24 01:23:44 +01:00
#include <stdint.h>
#include <avr/io.h>
#include <util/delay.h>
#include "MPU6050.h"
#include "i2c.h"
2024-03-24 02:35:05 +01:00
#include "uart.h"
2024-03-24 01:23:44 +01:00
// Function to initialize MPU-6050
void MPU6050_Init() {
2024-03-24 04:07:20 +01:00
DEBUG("MPU6050_init: Initializing...");
2024-03-24 01:23:44 +01:00
// Wake up MPU-6050 by writing to PWR_MGMT_1 register
2024-03-24 05:14:49 +01:00
if(!I2C_start(MPU6050_ADDR << 1 | TW_WRITE)) {
DEBUG("MPU6050_init: Failed to start I2C communication");
return;
}
2024-03-24 02:35:05 +01:00
// These two seem to be causing problems
2024-03-24 04:07:20 +01:00
DEBUG("MPU6050_init: Sending PWR_MGMT_1 register address");
2024-03-24 05:14:49 +01:00
if(!I2C_write(MPU6050_REG_PWR_MGMT_1)) {
DEBUG("MPU6050_init: Failed to write to PWR_MGMT_1 register");
return;
}
2024-03-24 02:35:05 +01:00
2024-03-24 04:07:20 +01:00
DEBUG("Writing 0x00 to PWR_MGMT_1 register");
2024-03-24 05:14:49 +01:00
if(!I2C_write(0x00)) { // Clear sleep mode bit
DEBUG("MPU6050_init: Failed to write to PWR_MGMT_1 register");
return;
}
2024-03-24 04:07:20 +01:00
DEBUG("MPU6050_init: Stopping...");
2024-03-24 01:23:44 +01:00
I2C_stop();
2024-03-24 04:07:20 +01:00
DEBUG("MPU6050_init: Initialized!");
2024-03-24 01:23:44 +01:00
}
// Function to read accelerometer data from MPU-6050
void MPU6050_Read_Accel(int16_t* accel_data) {
uint8_t buffer[6]; // Buffer to store accelerometer data
2024-03-24 04:07:20 +01:00
2024-03-24 01:23:44 +01:00
// Read accelerometer data starting from ACCEL_XOUT_H register
2024-03-24 05:14:49 +01:00
if(!I2C_start(MPU6050_ADDR << 1 | TW_WRITE)) {
DEBUG("MPU6050_Read_Accel: Failed to start I2C communication: %d", MPU6050_ADDR << 1 | TW_WRITE);
return;
}
2024-03-24 04:07:20 +01:00
DEBUG("MPU6050_Read_Accel: Sending ACCEL_XOUT_H register address");
2024-03-24 05:14:49 +01:00
if(I2C_write(MPU6050_REG_ACCEL_XOUT_H)) {
DEBUG("MPU6050_Read_Accel: Failed to write to ACCEL_XOUT_H register");
return;
}
2024-03-24 04:07:20 +01:00
DEBUG("MPU6050_Read_Accel: Reading accelerometer data");
2024-03-24 01:23:44 +01:00
I2C_start(MPU6050_ADDR << 1 | TW_READ);
for (int i = 0; i < 6; i++) {
2024-03-24 04:07:20 +01:00
DEBUG("MPU6050_Read_Accel: Reading byte %d", i);
2024-03-24 01:23:44 +01:00
buffer[i] = I2C_read(i < 5); // Read 6 bytes with ACK for all except last byte
}
2024-03-24 04:07:20 +01:00
DEBUG("MPU6050_Read_Accel: Stopping...");
2024-03-24 01:23:44 +01:00
I2C_stop();
// Combine high and low bytes for each axis
accel_data[0] = (buffer[0] << 8) | buffer[1]; // X-axis
accel_data[1] = (buffer[2] << 8) | buffer[3]; // Y-axis
accel_data[2] = (buffer[4] << 8) | buffer[5]; // Z-axis
}
// Function to read gyroscope data from MPU-6050
void MPU6050_Read_Gyro(int16_t* gyro_data) {
2024-03-24 04:07:20 +01:00
// TODO: Implement this function
2024-03-24 01:23:44 +01:00
}