AT24c16读写程序


// 24c16 read and write program
//





sbit wp=P1^6;
sbit SCL=P1^5; //I2C时钟和数据线
sbit SDA=P1^4;















void Delay1us() //@12.000MHz
{
_nop_();
_nop_();
}





void s24(void) //起始函数
{
SCL=1;
Delay1us();
SDA=0;
Delay1us();
SCL=0;
Delay1us();
}
void p24(void) //停止函数
{
SDA=0;
Delay1us();
SCL=1;
Delay1us();
SDA=1;
Delay1us();
SCL=0;
Delay1us();
}
unsigned char rd24(void) //从24c16读一字节数据
{
unsigned char i=8,j;
for(i=0;i<8;i++)
{
j<<=1;
SCL=1;
Delay1us();
if(SDA)
j |= 1;
SCL=0;
Delay1us();
}
SDA=1;
Delay1us();
return(j);
}


void wd24(unsigned char ch) //向24c16写一字节数据
{
unsigned char i=8;
for(i=0;i<8;i++)
{
if(ch & 0x80)
SDA=1;
else
SDA=0;
ch=(ch<<1);
SCL = 1;
Delay1us();
SCL=0;
Delay1us();
}


SDA=1;
Delay1us();
SCL=1;
Delay1us();
SCL=0;
Delay1us();


}
unsigned char read(unsigned int address)
{
unsigned char dd;
s24(); //开始条件
wd24(0xa0); //写器件地址(写命令)
wd24(address); //写数据地址
s24(); //开始条件
wd24(0xa1); //写器件地址(读命令)
dd=rd24(); //读 一字节
p24(); //停止条件
return(dd);
}
void write(unsigned int address,unsigned char dd)
{
s24(); //开始条件
wd24(0xa0); //写器件地址;
wd24(address); //写数据地址
wd24(dd); //写dd数据
p24(); //停止条件;
}









相关文档
最新文档