MPU6050 giving null data

I am trying to use mpu6050 with nrf52840, using bare metal programming. The program gets stuck at this loop - 

while (NRF_TWI0->EVENTS_TXDSENT == 0);
 what is the problem here? The full code I am using is  - 

#include <zephyr/kernel.h>
#include <zephyr/drivers/gpio.h>

#include <zephyr/drivers/adc.h>
#include <hal/nrf_saadc.h>


#include<drivers/include/nrfx_twim.h>
#include "stdio.h"
#include "string.h"



#include "nrf.h"


#define MPU6050_ADDRESS 0x68
#define MPU6050_PWR_MGMT_1 0x6B
#define MPU6050_ACCEL_XOUT_H 0x3B

void i2c_init(void) {
// Enable I2C (TWI) instance
NRF_TWI0->ENABLE = TWI_ENABLE_ENABLE_Enabled;
// Set frequency (100kHz)
NRF_TWI0->FREQUENCY = TWI_FREQUENCY_FREQUENCY_K100;
// Set SDA and SCL pins
NRF_TWI0->PSEL.SDA = 23; // Pin number for SDA
NRF_TWI0->PSEL.SCL = 22; // Pin number for SCL
// Enable the TWI instance
NRF_TWI0->ENABLE = TWI_ENABLE_ENABLE_Enabled;
}

void mpu6050_write_byte(uint8_t reg, uint8_t data) {
// Send address + write bit
NRF_TWI0->ADDRESS = MPU6050_ADDRESS;
NRF_TWI0->TXD = reg;
NRF_TWI0->TASKS_STARTTX = 1;
printk("Enter while loop\n");
while (NRF_TWI0->EVENTS_STOPPED == 0);
printk("Exit while loop\n");
NRF_TWI0->EVENTS_TXDSENT = 0;

// Send data
printk("Send data");
NRF_TWI0->TXD = data;
while (NRF_TWI0->EVENTS_TXDSENT == 0);
NRF_TWI0->EVENTS_TXDSENT = 0;

NRF_TWI0->TASKS_STOP = 1;
while (NRF_TWI0->EVENTS_STOPPED == 0);
NRF_TWI0->EVENTS_STOPPED = 0;
}

void mpu6050_init(void) {
printk("Inside MPU init\n");
mpu6050_write_byte(MPU6050_PWR_MGMT_1, 0x00); // Wake up MPU6050
printk("exit MPU init\n");
}

void mpu6050_read_bytes(uint8_t reg, uint8_t* buffer, uint8_t length) {
// Send address + write bit
NRF_TWI0->ADDRESS = MPU6050_ADDRESS;
NRF_TWI0->TXD = reg;
NRF_TWI0->TASKS_STARTTX = 1;
while (NRF_TWI0->EVENTS_TXDSENT == 0);
NRF_TWI0->EVENTS_TXDSENT = 0;

NRF_TWI0->TASKS_STARTRX = 1;
for (uint8_t i = 0; i < length; i++) {
while (NRF_TWI0->EVENTS_RXDREADY == 0);
buffer[i] = NRF_TWI0->RXD;
NRF_TWI0->EVENTS_RXDREADY = 0;
}

NRF_TWI0->TASKS_STOP = 1;
while (NRF_TWI0->EVENTS_STOPPED == 0);
NRF_TWI0->EVENTS_STOPPED = 0;
}

int main(void) {
uint8_t buffer[6];

i2c_init();
mpu6050_init();

while (1) {
mpu6050_read_bytes(MPU6050_ACCEL_XOUT_H, buffer, 6);
int16_t accel_x = (buffer[0] << 8) | buffer[1];
int16_t accel_y = (buffer[2] << 8) | buffer[3];
int16_t accel_z = (buffer[4] << 8) | buffer[5];

printk("%d ",accel_x);
printk("%d ",accel_y);
printk("%d ",accel_z);
}
}
Parents Reply Children
Related