新闻中心

EEPW首页>嵌入式系统>设计应用> 基于IIC总线协议的AT24C16操作程序

基于IIC总线协议的AT24C16操作程序

作者: 时间:2016-11-28 来源:网络 收藏

#include
#define uint unsigned int
#define uchar unsigned char
uchar shi,ge,t,sec,write;
uchar code table[]={0x3f,0x06,0x5b,0x4f,
0x66,0x6d,0x7d,0x07,
0x7f,0x6f};
sbit sda=P2^0;
sbit scl=P2^1;
void delayms(uint z)
{
uint x,y;
for(x=z;x>0;x--)
for(y=110;y>0;y--);
}
void delay()
{
;;
}
void display(uchar shi,uchar ge)//显示函数
{
P1=0xfd;
P0=table[ge];
delayms(5);
P1=0xfe;
P0=table[shi];
delayms(5);
}
void start()//起始信号
{
sda=1;
delay();
scl=1;
delay();
sda=0;
delay();
}
void stop()//终止信号
{
sda=0;
delay();
scl=1;
delay();
sda=1;
delay();
}
void respons()//应答信号
{
uchar i;
scl=1;
delay();
while((sda==1)&&(i<250))i++;
scl=0;
delay();
}
void init()//初始化
{
sda=1;
delay();
scl=1;
delay();
}
void write_byte(uchar date)//写数据函数
{
uchar i,temp;
temp=date;
for(i=0;i<8;i++)
{
temp=temp<<1;//将数据左移一位,最高位移至CY
scl=0;
delay();
sda=CY;
delay();
scl=1;
delay();
}
scl=0;
delay();
sda=1;
delay();
}
uchar read_byte()//读数据函数
{
uchar i,k;
scl=0;
delay();
sda=1;
delay();
for(i=0;i<8;i++)
{
scl=1;
delay();
k=(k<<1)|sda;//或运算,sda为0或者1,放到了k的最低位了,因k最低位为0
scl=0;
delay();
}
return k;//即为读到的数据
}
void write_add(uchar address,uchar date) //在某地址上写数据
{
start();//起始信号
write_byte(0xa0);//发送器件地址,最低位为0,表示主机发送
respons(); //应答
write_byte(address);//发送某器件存储单元地址
respons();//应答
write_byte(date); //写数据
respons();//应答
stop();//停止
}
uchar read_add(uchar address)//在某地址上读数据
{
uchar date;
start();//起始信号
write_byte(0xa0); //发送器件地址,最低位为0,表示主机发送
respons();//应答
write_byte(address);//发送某器件存储单元地址,表示要读此位置的数据
respons();//应答
start();//起始
write_byte(0xa1);//发送器件地址,最低位为1,表示主机接受数据
respons();
date=read_byte();
stop();
return date;
}
void main()
{
init();
sec=read_add(2);//地址随便写,在一定范围内
if(sec>100)//防止首次读出错误数据
sec=0;
TMOD=0x01;
ET0=1;
EA=1;
TH0=(65536-50000)/256;
TL0=(65536-50000)%6;
TR0=1;
while(1)
{
display(sec/10,sec);
if(write==1)//一秒写一次AT2416
{
write=0;
write_add(2,sec); //sec是十进制,在定义里面是作为二进制,自动转化??????
}
}
}
void t0()interrupt1
{
TH0=(65536-50000)/256;
TL0=(65536-50000)%6;
t++;
if(t==20)
{
t=0;
sec++;
write=1;
if(sec==100)
{
sec=0;
}
}
}

本文引用地址://m.amcfsurvey.com/article/201611/323002.htm


评论


技术专区

关闭