/*自己编写的单片机IO口模拟i2c底层库文件,已上机调试过*/
/************************************************************************/
/* Name: I2C.C */
/* Language: C51单片机编程语言 */
/* Platform: */
/* Author: FRANK FONG , huananfang@hotmail.com */
/* Date: 2010-05-21,上海; */
/* Version: */
/* Deion: I2C ,基于STK6032平台 */
/************************************************************************/
#include <string.h>
#include<stk6032.H>
#include <intrins.h>
#define DELAY_TIME 60
#define TRUE 1
#define FALSE 0
sbit SCL = P0^6;
sbit SDA = P0^7;
bit ACK;
/********** Definition 函数定义 ************/
/* 延时函数*/
void DELAY(unsigned int t)
{
while(t!=0)
t--;
}
/*启动I2C总线的函数,当SCL为高电平时使SDA产生一个负跳变*/
void I2C_Start(void)
{
SDA=1;
DELAY(DELAY_TIME);
SCL=1;
DELAY(DELAY_TIME);
SDA=0;
DELAY(DELAY_TIME);
SCL=0;
DELAY(DELAY_TIME);
}
/*终止I2C总线,当SCL为高电平时使SDA产生一个正跳变*/
void I2C_Stop(void)
{
SDA=0;
DELAY(DELAY_TIME);
SCL=1;
DELAY(DELAY_TIME);
SDA=1;
DELAY(DELAY_TIME);
SCL=0;
DELAY(DELAY_TIME);
}
/*发送,在SCL为高电平时使SDA信号为低 ,SEND ACK*/
void SEND_0(void)
{
SDA=0;
DELAY(DELAY_TIME);
SCL=1;
DELAY(DELAY_TIME);
SCL=0;
DELAY(DELAY_TIME);
}
/*发送,在SCL为高电平时使SDA信号为高*/
void SEND_1(void)
{
SDA=1;
DELAY(DELAY_TIME);
SCL=1;
DELAY(DELAY_TIME);
SCL=0;
DELAY(DELAY_TIME);
}
/* 发送完一个字节后检验设备的应答信号 */
bit Check_Acknowledge(void)
{
SDA=1;
DELAY(DELAY_TIME);
SCL=1;
DELAY(DELAY_TIME);
ACK=SDA;
DELAY(DELAY_TIME);
SCL=0;
DELAY(DELAY_TIME);
if(ACK==1)
return FALSE;
else
return TRUE;
}
/*向I2C总线写一个字节*/
void WriteI2C_1_Byte(unsigned char b)
{
unsigned char i;
for(i=0;i<8;i++)
{
if((b<<i)&0x80)
SEND_1();
else
SEND_0();
}
if(!Check_Acknowledge())
{
I2C_Stop();
}
}
/*向I2C总线写两个字节*/
void WriteI2C_2_Byte(unsigned int b)
{
WriteI2C_1_Byte((b >> 8) & 0xFF);
WriteI2C_1_Byte(b & 0xFF);
}
/*从I2C总线读一个字节*/
unsigned char ReadI2C_1_Byte(void)
{
unsigned char b=0,i;
for(i=0;i<8;i++)
{
/*释放总线*/
SDA = 1;
DELAY(DELAY_TIME);
/*接受数据*/
SCL = 1;
DELAY(DELAY_TIME);
ACK=SDA;
DELAY(DELAY_TIME);
SCL=0;
if(ACK==1)
{
b=b<<1;
b=b|0x01;
}
else
b=b<<1;
}
return b;
}
/*向器件寄存器组写数据*/
void Write_N_Bytes(unsigned int *buffer,unsigned char n,unsigned char addr)
{
unsigned char i=0;
I2C_Start();
/*the AR1010device address*/
WriteI2C_1_Byte(0x20);
/*the AR1010register address*/
WriteI2C_1_Byte(addr);
for(i=0;i<n;i++)
{
WriteI2C_2_Byte(buffer);
}
I2C_Stop();
}
/*读器件寄存器数据*/
unsigned int Read_2_Bytes(unsigned char addr)
{
unsigned int a=0;
unsigned int b=0;
I2C_Start();
WriteI2C_1_Byte(0x20);
/*reg_address*/
WriteI2C_1_Byte(addr);
I2C_Start();
WriteI2C_1_Byte(0x21);
a=ReadI2C_1_Byte();
/* master发送应答*/
SEND_0();
a<<=8;
b=ReadI2C_1_Byte();
/* master发送应答*/
SEND_1();
I2C_Stop();
return a+=b;
} |