新聞中心

EEPW首頁(yè) > 嵌入式系統(tǒng) > 設(shè)計(jì)應(yīng)用 > 基于IIC總線協(xié)議的AT24C16操作程序

基于IIC總線協(xié)議的AT24C16操作程序

作者: 時(shí)間:2016-11-28 來(lái)源:網(wǎng)絡(luò) 收藏

#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) //顯示函數(shù)
{
P1=0xfd;
P0=table[ge];
delayms(5);
P1=0xfe;
P0=table[shi];
delayms(5);
}
void start() //起始信號(hào)
{
sda=1;
delay();
scl=1;
delay();
sda=0;
delay();
}
void stop() //終止信號(hào)
{
sda=0;
delay();
scl=1;
delay();
sda=1;
delay();
}
void respons() //應(yīng)答信號(hào)
{
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) //寫(xiě)數(shù)據(jù)函數(shù)
{
uchar i,temp;
temp=date;
for(i=0;i<8;i++)
{
temp=temp<<1;//將數(shù)據(jù)左移一位,最高位移至CY
scl=0;
delay();
sda=CY;
delay();
scl=1;
delay();
}
scl=0;
delay();
sda=1;
delay();
}
uchar read_byte() //讀數(shù)據(jù)函數(shù)
{
uchar i,k;
scl=0;
delay();
sda=1;
delay();
for(i=0;i<8;i++)
{
scl=1;
delay();
k=(k<<1)|sda; //或運(yùn)算,sda為0或者1,放到了k的最低位了,因k最低位為0
scl=0;
delay();
}
return k; //即為讀到的數(shù)據(jù)
}
void write_add(uchar address,uchar date) //在某地址上寫(xiě)數(shù)據(jù)
{
start(); //起始信號(hào)
write_byte(0xa0); //發(fā)送器件地址,最低位為0,表示主機(jī)發(fā)送
respons(); //應(yīng)答
write_byte(address);//發(fā)送某器件存儲(chǔ)單元地址
respons(); //應(yīng)答
write_byte(date); //寫(xiě)數(shù)據(jù)
respons(); //應(yīng)答
stop(); //停止
}
uchar read_add(uchar address) //在某地址上讀數(shù)據(jù)
{
uchar date;
start(); //起始信號(hào)
write_byte(0xa0); //發(fā)送器件地址,最低位為0,表示主機(jī)發(fā)送
respons(); //應(yīng)答
write_byte(address);//發(fā)送某器件存儲(chǔ)單元地址,表示要讀此位置的數(shù)據(jù)
respons(); //應(yīng)答
start(); //起始
write_byte(0xa1);//發(fā)送器件地址,最低位為1,表示主機(jī)接受數(shù)據(jù)
respons();
date=read_byte();
stop();
return date;
}
void main()
{
init();
sec=read_add(2);//地址隨便寫(xiě),在一定范圍內(nèi)
if(sec>100)//防止首次讀出錯(cuò)誤數(shù)據(jù)
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)//一秒寫(xiě)一次AT2416
{
write=0;
write_add(2,sec); //sec是十進(jìn)制,在定義里面是作為二進(jìn)制,自動(dòng)轉(zhuǎn)化??????
}
}
}
void t0() interrupt 1
{
TH0=(65536-50000)/256;
TL0=(65536-50000)%6;
t++;
if(t==20)
{
t=0;
sec++;
write=1;
if(sec==100)
{
sec=0;
}
}
}

本文引用地址:http://m.butianyuan.cn/article/201611/323002.htm


評(píng)論


技術(shù)專區(qū)

關(guān)閉