SC7A20获取三轴加速度值(I2C)
1. I2C.h
#ifndef __I2C_H
#define __I2C_H
#include "config.h"
sbit I2C_SCL=P3^2;
sbit I2C_SDA=P3^3;
#define I2C_SCL_Clr() I2C_SCL=0
#define I2C_SCL_Set() I2C_SCL=1
#define I2C_SDA_Clr() I2C_SDA=0
#define I2C_SDA_Set() I2C_SDA=1
void Start();
void SendData(char dat);
void RecvACK();
char RecvData(u8 SF_Ack);
void SendACK();
void SendNAK();
void Stop();
#endif
2. I2C.c (IO口模拟I2C)
#include "I2C.h"
void I2C_delay(void)
{
u8 t=1;
while(t--);
}
void Start()
{
I2C_SDA_Set();
I2C_SCL_Set();
I2C_delay();
I2C_SDA_Clr();
I2C_delay();
I2C_SCL_Clr();
}
void SendData(u8 dat)
{
u8 i;
for(i=0;i<8;i++)
{
I2C_SCL_Clr();
if(dat&0x80)
{
I2C_SDA_Set();
}
else
{
I2C_SDA_Clr();
}
I2C_delay();
I2C_SCL_Set();
I2C_delay();
I2C_SCL_Clr();
dat<<=1;
}
}
void RecvACK()
{
I2C_SDA_Set();
I2C_delay();
I2C_SCL_Set();
I2C_delay();
I2C_SCL_Clr();
I2C_delay();
}
char RecvData(u8 SF_Ack)
{
u8 Rb_Cnt = 0;
u8 RByte = 0;
for(Rb_Cnt=0; Rb_Cnt<8; Rb_Cnt++)
{
I2C_SCL_Clr();
I2C_delay();
I2C_SCL_Set();
RByte <<= 1;
if(I2C_SDA)
{
RByte++;
}
I2C_delay();
}
if(!SF_Ack)
{
SendNAK();
}
else
{
SendACK();
}
return RByte;
}
void SendACK()
{
I2C_SCL_Clr();
I2C_SDA_Clr();
I2C_delay();;
I2C_SCL_Set();
I2C_delay();;
I2C_SCL_Clr();
}
void SendNAK()
{
I2C_SCL_Clr();
I2C_SCL_Set();
I2C_delay();;
I2C_SCL_Set();
I2C_delay();;
I2C_SCL_Clr();
}
void Stop()
{
I2C_SDA_Clr();
I2C_SCL_Set();
I2C_delay();
I2C_SDA_Set();
}
3. SC7A20.h
#ifndef __SC7A20_H
#define __SC7A20_H
#include "config.h"
#include "delay.h"
#define SC7A20_I2C_WADDR 0x30
#define SC7A20_I2C_RADDR 0x31
void SC7A20_Init();
#endif
4. SC7A20.c
#include "SC7A20.h"
#include "I2C.h"
#include "stdio.h"
void SC7A20_Write_Byte(u8 RAddr, u8 WData)
{
Start();
SendData(SC7A20_I2C_WADDR);
RecvACK();
SendData(RAddr);
RecvACK();
SendData(WData);
RecvACK();
Stop();
}
void SC7A20_Read_Byte(u8 RAddr, u8 *RData)
{
Start();
SendData(SC7A20_I2C_WADDR);
RecvACK();
SendData(RAddr);
RecvACK();
Start();
SendData(SC7A20_I2C_RADDR);
RecvACK();
*RData = RecvData(0);
Stop();
}
void SC7A20_Init()
{
SC7A20_Write_Byte(0x20,0x77);
SC7A20_Write_Byte(0x21,0x88);
SC7A20_Write_Byte(0x23,0x88);
}
int SC7A20_Get_ACCD(u8 accd_lsb,u8 accd_msb)
{
u8 accd_l,accd_m = 0;
unsigned int temp;
int accd;
SC7A20_Read_Byte(accd_lsb,&accd_l);
SC7A20_Read_Byte(accd_msb,&accd_m);
temp &= 0x0000;
temp |= accd_m;
temp <<= 8;
temp &= 0xff00;
temp |= accd_l;
if(temp&0x8000)
{
temp >>= 4;
temp |= 0xf000;
}
else
{
temp >>= 4;
temp &= 0x0fff;
}
accd = temp*1;
return accd;
}
void SC7A20_GetInfo()
{
int x,y,z = 0;
unsigned char i = 16;
for(i=8;i>0;i--)
{
x += SC7A20_Get_ACCD(0x28,0x29);
y += SC7A20_Get_ACCD(0x2A,0x2B);
z += SC7A20_Get_ACCD(0x2C,0x2D);
}
x /= 8;
y /= 8;
z /= 8;
printf("x:%hd mg, y:%hd mg, z:%hd mg \r\n",x,y,z);
}