Hello,
I am trying to interface the MPU6050 with Cypress PSoC 5 LP097 and read out the values. However I find that the values I read out are always zeroes. I have been struggling on this issue for quite long and do not know how to proceed ahead. Any tips are appreciated.
Below is the code :
File : MPU6050.c
void Wakeup(void)
{
writeBit(MPU6050_RA_PWR_MGMT, MPU6050_PWR1_SLEEP_BIT,0);
}
void readbyte(uint8_t reg, uint8_t *data)
{
readbytes(reg,1,data);
}
bool readbytes(uint8_t reg, uint8_t len, uint8_t *data)
{
int i = 0;
bool readSuccess = false;
while (I2C_MSTR_NO_ERROR == I2C_MasterSendStart(MPU6050_DEVICE_ADDRESS, I2C_WRITE_XFER_MODE));
while (I2C_MSTR_NO_ERROR == I2C_MasterWriteByte(reg));
while (I2C_MSTR_NO_ERROR == I2C_MasterSendRestart(MPU6050_DEVICE_ADDRESS, I2C_READ_XFER_MODE));
while (i < (len-1) ) {
data[i++] = I2C_MasterReadByte(I2C_ACK_DATA);
}
data = I2C_MasterReadByte(I2C_NAK_DATA);
readSuccess = true;
I2C_MasterSendStop();
UART_PutString("I2C read completed \n");
return readSuccess;
}
void writeBit(uint8_t reg, uint8_t num, uint8_t data)
{
uint8 pwr_mgmt_reg = 0;
readbyte(reg,&pwr_mgmt_reg); // read the current value of pwr_mgmt_register
UART_PutString("Pw mgmnt reg value = ");
UART_PutChar(pwr_mgmt_reg + CONVERT_TO_ASCII);
UART_PutString("\n");
pwr_mgmt_reg &= ~(1<<num); //set the sleep bit in the register
// pwr_mgmt_reg &= 0x3F;
writebyte(reg,pwr_mgmt_reg); //write back after setting the pin.
}
void writebyte(uint8_t reg, uint8_t data)
{
//uint8 i = 0;
while (I2C_MSTR_NO_ERROR == I2C_MasterSendStart(MPU6050_DEVICE_ADDRESS, I2C_WRITE_XFER_MODE)); //start sequence
while (I2C_MSTR_NO_ERROR == I2C_MasterWriteByte(reg)); //reach the reg address.
//I2C_MasterSendRestart(SLAVE_ADDR, 0x00);
while (I2C_MSTR_NO_ERROR == I2C_MasterWriteByte(data)); //write the data
I2C_MasterSendStop(); //stop sequence
UART_PutString("-----I2C write completed \n");
}
bool readGyroData(uint8_t* rBuffer, uint8_t length)
{
return readbytes(MPU6050_RA_ACCEL_XOUT_H, length,rBuffer);
}
File main.c :
#include "MPU6050.h"
#include "project.h"
#include <stdio.h>
#include <stdbool.h>
#define BUFFER_SIZE 0x1F4u
#define CONVERT_TO_ASCII 0x30
#define MPU6050_DEVICE_ADDRESS 0x68u
#define MPU6050_RA_ACCEL_XOUT_H 0x3Bu
#define MPU6050_RA_PWR_MGMT 0x6Bu
#define MPU6050_PWR1_SLEEP_BIT 0x06u
/*MPU data read buffer*/
uint8_t I2C_RBUFFER[BUFFER_SIZE];
bool readGyroData(uint8_t* rBuffer, uint8_t length);
int main(void)
{
CyGlobalIntEnable; /* Enable global interrupts. */
uint8 i;
/* Place your initialization/startup code here (e.g. MyInst_Start()) */
I2C_Start();
UART_Start();
Wakeup();
for(;;)
{
/* Place your application code here. */
if (true == readGyroData(I2C_RBUFFER,0x0E)) { //14 bytes to read including temp.
UART_PutString("GY 521 data : \n");
for(i = 0; i < 14; i++) {
UART_PutCRLF(I2C_RBUFFER + CONVERT_TO_ASCII);
}
CyDelay(50);
}
else {
UART_PutString("no data to read");
}
}
}