帮我用C语言写一个51单片机的MPU6050驱动代码
时间: 2024-01-25 15:02:52 浏览: 79
由于无法运行和测试,以下代码仅供参考。
#include <reg52.h>
#include <intrins.h>
sbit SDA = P2^0;
sbit SCL = P2^1;
void IIC_Delay(unsigned char n)
{
while(n--)
{
_nop_();
}
}
void IIC_Start()
{
SDA = 1;
SCL = 1;
IIC_Delay(1);
SDA = 0;
IIC_Delay(1);
SCL = 0;
IIC_Delay(1);
}
void IIC_Stop()
{
SDA = 0;
SCL = 1;
IIC_Delay(1);
SDA = 1;
IIC_Delay(1);
}
void IIC_WriteByte(unsigned char dat)
{
unsigned char i;
for(i=0;i<8;i++)
{
SDA = (dat&0x80)>>7;
dat <<= 1;
SCL = 1;
IIC_Delay(1);
SCL = 0;
IIC_Delay(1);
}
SDA = 1;
SCL = 1;
IIC_Delay(1);
SCL = 0;
IIC_Delay(1);
}
unsigned char IIC_ReadByte()
{
unsigned char i;
unsigned char dat = 0;
SDA = 1;
for(i=0;i<8;i++)
{
SCL = 1;
IIC_Delay(1);
dat <<= 1;
dat |= SDA;
SCL = 0;
IIC_Delay(1);
}
return dat;
}
void MPU6050_WriteReg(unsigned char reg, unsigned char dat)
{
IIC_Start();
IIC_WriteByte(0xD0);
IIC_WriteByte(reg);
IIC_WriteByte(dat);
IIC_Stop();
}
unsigned char MPU6050_ReadReg(unsigned char reg)
{
unsigned char dat;
IIC_Start();
IIC_WriteByte(0xD0);
IIC_WriteByte(reg);
IIC_Start();
IIC_WriteByte(0xD1);
dat = IIC_ReadByte();
IIC_Stop();
return dat;
}
void MPU6050_Init()
{
MPU6050_WriteReg(0x6B,0x00); //解除休眠状态
MPU6050_WriteReg(0x1A,0x06); //配置低通滤波器
MPU6050_WriteReg(0x1B,0x18); //配置陀螺仪量程范围
MPU6050_WriteReg(0x1C,0x10); //配置加速计量程范围
}
void MPU6050_ReadData(short int *Data)
{
unsigned char i;
unsigned char buf[14];
IIC_Start();
IIC_WriteByte(0xD0);
IIC_WriteByte(0x3B);
IIC_Start();
IIC_WriteByte(0xD1);
for(i=0;i<14;i++)
{
buf[i] = IIC_ReadByte();
if(i != 13)
{
IIC_WriteByte(0x01);
}
}
IIC_Stop();
Data[0] = (buf[0]<<8) | buf[1];
Data[1] = (buf[2]<<8) | buf[3];
Data[2] = (buf[4]<<8) | buf[5];
Data[3] = (buf[6]<<8) | buf[7];
Data[4] = (buf[8]<<8) | buf[9];
Data[5] = (buf[10]<<8) | buf[11];
}
void main()
{
short int Data[6];
MPU6050_Init();
while(1)
{
MPU6050_ReadData(Data);
}
}
阅读全文