这个我的代码 :
void Start()
{
SetSCL;
SetSDA;
DelayuS(5);
ClrSDA;
DelayuS(5);
ClrSCL;
}
void Stop()
{
ClrSDA;
SetSCL;
DelayuS(5);
SetSDA;
DelayuS(5);
ClrSDA;
}
//写单字节数据
void Write(uint8_t sdate)
{
uint8_t i;
for(i=0;i<8;i++)
{
DelayuS(5);
if( (sdate&BIT7) == BIT7 )
SetSDA;
else
ClrSDA;
SetSCL;
DelayuS(5);
ClrSCL;
sdate = sdate<<1;
}
}
//等待应答 返回0则表示接受到非应答 有错误
uint8_t ACK()
{
SetSDA;
LPC_GPIO0->FIODIR &= (~BIT23);
SetSCL;
DelayuS(5);
if( (LPC_GPIO0->FIOPIN & BIT23) == BIT23 )
return 0;
ClrSCL;
LPC_GPIO0->FIODIR |= BIT23;
return 1;
}
//接受数据后发送应答
void send_ACK()
{
LPC_GPIO0->FIODIR |= BIT23;
ClrSDA;
SetSCL;
DelayuS(5);
ClrSCL;
}
//接收单字节数据
uint8_t receive()
{
uint8_t i,j,rdate;
j=0x80;
rdate = 0;
LPC_GPIO0->FIODIR &= (~BIT23);
for(i=0;i<8;i++)
{
SetSCL;
if( (LPC_GPIO0->FIOPIN & BIT23) == BIT23)
rdate |= j;
else
rdate &= ~j;
j = j>>1;
DelayuS(5);
ClrSCL;
DelayuS(5);
}
return rdate;
}
void SentData(uint8_t Slave_Address,uint8_t REG_Address,uint8_t REG_Data)
{
Start();
Write(Slave_Address);
ACK();
Write(REG_Address);
ACK();
Write(REG_Data);
ACK();
Stop();
DelaymS(2);
}
uint8_t Read_Gyro(uint8_t Slave_Address,uint8_t REG_Address)
{
Start();
Write(Slave_Address);
ACK();
Write(REG_Address);
ACK();
Start();
Write(Slave_Address+1);
ACK();
gxH = receive();
send_ACK();
gxL = receive();
send_ACK();
gyH = receive();
send_ACK();
gyL = receive();
send_ACK();
gzH = receive();
send_ACK();
gzL = receive();
Stop();
return 1;
}
uint8_t Read_Accel(uint8_t Slave_Address,uint8_t REG_Address)
{
Start();
Write(Slave_Address);
ACK();
Write(REG_Address);
ACK();
Start();
Write(Slave_Address+1);
ACK();
gxH = receive();
send_ACK();
gxL = receive();
send_ACK();
gyH = receive();
send_ACK();
gyL = receive();
send_ACK();
gzH = receive();
send_ACK();
gzL = receive();
Stop();
return 1;
}
int main(void)
{
SystemInit(); // 主要完成系统时钟初始化等功能
LPC_GPIO0->FIODIR |= (BIT23|BIT25);
SentData(MPU6050_Addr,PWR_MGMT_1,0x80); //复位
DelaymS(50);
SentData(MPU6050_Addr,PWR_MGMT_1,0x00);
SentData(MPU6050_Addr,SMPLRT_DIV,0x07);
SentData(MPU6050_Addr,CONFIG,0x06);
SentData(MPU6050_Addr,GYRO_CONFIG,0x18); //量程2000deg/s
SentData(MPU6050_Addr,ACCEL_CONFIG,0x01); //量程2g
while(1)
{
Read_Accel(MPU6050_Addr,ACCEL_XOUT_H);
//Read_Gyro(MPU6050_Addr,GYRO_XOUT_H);
DelaymS(100);
}
}