#include
__CONFIG(1,XT) ;
//晶振为外部4M
__CONFIG(2,WDTDIS) ;
//看门狗关闭
__CONFIG(4,LVPDIS) ;
//禁止低电压编程
#define uint unsigned int
#define uchar unsigned char
#define nop NOP()
#define en RB3
#define rw RB4
#define rs RB5
#define scl RC5
#define sda RC6
uchar p[]="TIME:";
uchar q[]="week";
void delayms(uint z)
{
uint i,j;
for(i=0;i<=110;i++)
for(j=0;j<=z;j++);
}
void write_com(uchar com)
{
rs=0;
rw=0;
delayms(5);
en=1;
delayms(5);
PORTD=com;
en=0;
delayms(5);
}
void write_dat(uchar dat)
{
rs=1;
rw=0;
delayms(5);
en=1;
delayms(5);
PORTD=dat;
en=0;
delayms(5);
}
void init_1602()
{
write_com(0x38);
write_com(0x0c);
write_com(0x06);
write_com(0x01);
}
void usdelay()
{
nop;
}
void init_24c() //初始化24C,就是把两根线拉高
{
TRISC6=0;
scl=1;
sda=1;
usdelay();
}
void start() //开始信号,根据时序图(sx)
{
TRISC6=0;
scl=1;
usdelay();
sda=1;
usdelay();
sda=0;
}
void stop() //结束信号 sx
{
TRISC6=0;
scl=1;
usdelay();
sda=0;
usdelay();
sda=1;
}
void ack() //不知道为什么,在PIC中不能用ack,好像一用就会出错= =?
{
uchar i;
TRISC6=0;
sda=1;
nop;
TRISC6=1;
scl=1;
nop;
while(sda==1&&i<10)i++;
scl=0;
}
void write_byte(uchar dat) //写字节 sx
由于不仅要写数据,还要写地址,所以只能先写字节的最高位R7,最后写最低位R0
{
uchar i;
TRISC6=0;
sda=0;
scl=0;
nop;
for(i=0;i<=8;i++)
{
sda=(dat&0x80)>>7;
nop;
scl=1;
nop;
scl=0;
dat<<=1;
nop;
}
}
uchar read_byte() //读字节 sx 先读高位R7,最后读地位R0
{
uchar i,dat=0;
TRISC6=1;
sda=0;
usdelay();
scl=1;
usdelay();
for(i=0;i<8;i++)
{
dat<<=1;
usdelay();
scl=1;
nop;
dat=dat|sda;
nop;
scl=0;
usdelay();
}
return dat;
}
void write_add(uchar add,uchar dat) //写数据到地址 sx 注意不要用ack
{
start();
write_byte(0xa2);
write_byte(add);
write_byte(dat);
stop();
}
uchar read_add(uchar add) //从地址读数据 sx 注意不要用ack
{
uchar dat;
start();
write_byte(0xa2);
write_byte(add);
start();
write_byte(0xa3);
dat=read_byte();
stop();
return dat;
}
void main()
{
uchar temp=0;
uchar ii;
ADCON1=0x06;
TRISC5=0;
TRISB=0B11000111;
TRISD=0x00;
init_1602();
init_24c();
write_com(0x80+0x40+2);
write_dat(':');
write_com(0x80+0x40+5);
write_dat(':');
write_com(0x80);
for(ii=1;ii<=5;ii++)
write_dat(*(p+ii-1));
write_com(0x80+0x40+9);
for(ii=1;ii<=4;ii++)
write_dat(*(q+ii-1));
write_com(0x80+6);
write_dat('2');
write_dat('0');
write_com(0x80+10);
write_dat('.');
write_com(0x80+13);
write_dat('.');
while(1)
{
temp=read_add(0x08);//年
write_com(0x80+8);
write_dat(0x30+((temp>>4)&0x07));
write_dat(0x30+(temp&0x0f));
temp=read_add(0x07);//月
write_com(0x80+11);
write_dat(0x30+((temp>>4)&0x01));
write_dat(0x30+(temp&0x0f));
temp=read_add(0x06);//星期
write_com(0x80+0x40+14);
write_dat(0x30+temp);
temp=read_add(0x05);// 日
write_com(0x80+14);
write_dat(0x30+((temp>>4)&0x03));
write_dat(0x30+(temp&0x0f));
temp=read_add(0x04);//时
write_com(0x80+0x40);
write_dat(0x30+((temp>>4)&0x03));
write_dat(0x30+(temp&0x0f));
temp=read_add(0x03);//分
write_com(0x80+0x40+3);
write_dat(0x30+((temp>>4)&0x07));
write_dat(0x30+(temp&0x0f));
temp=read_add(0x02);//秒
write_com(0x80+0x40+6);
write_dat(0x30+((temp>>4)&0x07));
write_dat(0x30+(temp&0x0f));
}
}