#include<pic.h>
#define uchar unsigned char
#define uint unsigned int
#define add 0x03
uchar date[4]={1,2,3,4};
uchar i;
uchar d[4]; //读回来的数据放到里面
void init();
void write();
void read();
void led();
void delay(uint time1)
{
uint q,w;
for(q = 0;q < time1; q++)
{
for(w = 0;w < 30; w++);
}
}
void init()
{
TRISD=0X00;
PORTD=0X11;
TRISC=0X00; //RC3RC4是SCL和SDA
PORTC=0X00;
TRISB=0X01; //RB0初始化为高,连接按键
PORTB=0X01;
SSPSTAT=0X80;
SSPCON=0X38; //IIC配置接口 选择时钟
SSPCON2=0X00;
SSPADD=0X09; //100K=4M/4*(ADD+1)
}
void write()
{
SEN=1;
while(!SSPIF);
SSPIF=0;
SSPBUF=0xA0;
while(!SSPIF);
SSPIF=0;
SSPBUF=add;
while(!SSPIF);
SSPIF=0;
for(i=0;i<4;i++)
{
SSPBUF=date[i]; //写四个数据到EEPROm
while(!SSPIF);
SSPIF=0;
}
PEN=1;
while(!SSPIF);
SSPIF=0;
}
void read()
{
SEN=1;
while(!SSPIF);
SSPIF=0;
SSPBUF=0xA0;
while(!SSPIF);
SSPIF=0;
SSPBUF=add;
while(!SSPIF);
SSPIF=0;
RSEN=1;
while(!SSPIF);
SSPIF=0;
SSPBUF=0xA1;
while(!SSPIF);
SSPIF=0;
for(i=0;i<4;i++)
{
RCEN=1;
while(!SSPIF);
d[i]=SSPBUF;
SSPBUF=0;
if(i>=4)
{
ACKDT=1;
}
else
{
ACKDT=0;
}
ACKEN=1;
while(!SSPIF);
SSPIF=0;
}
PEN=1;
while(!SSPIF);
SSPIF=0;
}
void led()
{
if(RB0==0)
{
for(i=0;i<=3;i++)
{
PORTD=d[i];
delay(5000);
}
}
}
void main()
{
__CONFIG(XT&WDTDIS&LVPDIS);
init();
write();
delay(10);
read();
while(1)
{
led();
}
} |