求一段基于51单片机的AT24C02的存储和调用程序(C语言)

实现功:1)单片机能向AT24C02存入密码
2)读出AT24C02中存储的密码

#include<c8051f410.h>
#include<intrins.h>
typedef unsigned char uchar;
typedef unsigned int uint;
sbit SDA=P1^0;
sbit SCL=P1^1;
void delay(void)
{
uint m;
for(m=0;m<0xffff;m++)
_nop_();
}
void start (void) // IIC开始
{
SDA=1;
SCL=1; //在至少4u秒期间SDA从高电平到低电平
SDA=0;
SCL=0;
}
void stop(void) // IIC结束
{
SDA=0;
SCL=1; //在至少4u秒期间SDA从低电平到高电平
SDA=1;
SCL=0;
}
uchar check(void) // 检查应答信号
{
uchar ACK;
SDA=1;
SCL=0;
SCL=1;
if (SDA == 1)
{
ACK = 1;
}
else
{
ACK = 0;
}
return(ACK);
}
void send(uchar _data) // 发送一个字节
{
uchar bitcount=8; //发送8位
SCL=1;
do
{
if((_data&0x80)==0x80)
{
SDA=1; //发送1
}
else
{
SDA=0; //发送0
}
SCL=0; // 在时钟大于4u秒期间写数据
_data=_data<<1;
bitcount--;
SCL=1;
}while(bitcount);
}
uchar recive(void) //接受一个字节
{
uchar temp1=0;
uchar bitcount1=8;
SDA=1; //置输入
do
{
SCL=1; //在时钟大于4u秒期间读数据
if(SDA) //读1
{
temp1=temp1|0x01;
}
else //读0
{
temp1=temp1&0xfe;
}
SCL=0;
if(bitcount1-1)
{
temp1=temp1<<1;
}
bitcount1--;
SCL=1;
}while(bitcount1);
return(temp1);
}
void ack(void) //发送继续读信号
{
SDA=0;
SCL=0;
SCL=1;
}
void nack(void) //停止继续读
{
SDA=1;
SCL=0;
SCL=1;
}
void wrtoROM(uchar *_data,uint address,uchar num) //给24LC256写数据
{
uint i;
uint adrl=address%256; //低8位地址
uint adrh=address/256; //高8位地址
start(); //起始信号
send(0xa4); //写主控器识别地址,本人是a2
while(check()); //等待应答
send(adrh); //送数据高8位地址
while(check()); //等待应答
send(adrl); //送数据低8位地址
while(check()); //等待应答
for(i=0;i<num;i++,_data++)
{
send(*_data); //发送数据
while(check()); //等待应答
}
stop(); //停止
delay(); //延时,下次发数据
}
void rdfromROM(uchar *_pdata,uint address,uchar num2) //从24LC256中读数据
{
uint adrl;
uint adrh;
uchar j;
for(j=0;j<num2;j++,_pdata++)
{
adrl=address%256; //地址低位
adrh=address/256; //地址高位
start(); //开始
/* send(0xa2); //写主控器识别地址(写),本人是a2
while(check()); //等待应答
send(adrh); //送高位
while(check()); //等待应答
send(adrl); //送低位
while(check()); //等待应答
start(); //开始读数据
send(0xa3); //写主控器识别地址(读)
while(check()); //等待应答 */

send(0xa5); //写主控器识别地址(写),本人是a2
while(check()); //等待应答
send(adrh); //送高位
while(check()); //等待应答
send(adrl); //送低位
while(check()); //等待应答
*_pdata=recive();
// nack();
stop();
address=address+1; //指向下一个地址
}
}
main()
{
uint h,n;
uchar str[64]={0x5d,0x5d,0x32,0x18,0x6c,0x88,0xa0,0x1d,0x20,0x08};
SCL=1;
SDA=1;
for(n=0;n<255;)
{
wrtoROM(str,n,64); //写一页的数据,根据24LC256一页是64个字节
n=n+64; //写下一页数据
}

for(h=0;h<64;h++) //数组清0
{
str[h]=0x21;
}
delay();
rdfromROM(str,0x02,64); //读从地址0开始的一页数据
while(1)
{ ;
}
}追问

请问主控器识别地址,如何确定?

追答

地址都是由主控cpu发出的,同一时刻只能有一个主控元件,具体的你查看一下IIC通信协议便知。

温馨提示:答案为网友推荐,仅供参考
相似回答