/************************************************
名称:DS1302实时时钟显示程序
说明:从DS1302中读取时钟数据,在LCD上显示日期和时间
*************************************************/
#include <reg51.h>
#include <intrins.h>
#include <string.h>
#define uchar unsigned char
#define uint unsigned int
sbit IO = P1^0; //数据线
sbit SCLK = P1^1; //时钟线
sbit RST = P1^2; //复位线
sbit RS = P2^0;
sbit RW = P2^1;
sbit EN = P2^2;
uchar *WEEK[] = {"SUN","MON","TUS","WEN","THU","FRI","SAT"}; //周一至周六
uchar LCD_BUF_1[]={"DATE 00-00-00 "};
uchar LCD_BUF_2[]={"TIME 00:00:00 "}; //写此条时注意空格
void GetDateTime();
uchar DateTime[7];
void Delayms(uint ms)
{
uchar i;
while(ms--)
{
for(i=0;i<120;i++);
}
}
void Write_LCD_Command(uchar cmd)
{
//while((Busy_Check()&0x80)==0x80);
//Busy_Check(); //两种写法都行
RS = 0;
RW = 0; //写状态
EN = 0;
P0 = cmd;
EN = 1;
Delayms(1);
EN = 0;
}
void Write_LCD_Data(uchar dat) //发送数据
{
// while((Busy_Check()&0x80)==0x80);
// Busy_Check();
RS = 1; //数据寄存器
RW = 0; //写状态
EN = 0;
P0 = dat; //数据字节放到LCD端口
EN = 1;
Delayms(1);
EN = 0;
}
void Initialize_LCD() //初始化
{
Write_LCD_Command(0x38); //置功能 ,8位,双行,5*7点阵
Delayms(1);
Write_LCD_Command(0x01); //清屏
Delayms(1);
Write_LCD_Command(0x06); //字符进入模式递增
Delayms(1);
Write_LCD_Command(0x0c); //显示开关
Delayms(1);
}
void ShowString(uchar x,uchar y,uchar *str) //在指定位置显示
{
uchar i = 0;
if(y == 0)
Write_LCD_Command(0x80 | x); //x为第x列字符位置,y为第y行
if(y == 1)
Write_LCD_Command(0xc0 | x);
for(i=0;i<16;i++)
{
Write_LCD_Data(str[i]);
}
}
//向DS1302写入一字节
void Write_A_Byte_TO_DS1302(uchar x)
{
uchar i;
for(i=0;i<8;i++)
{
IO=x&0x01;SCLK=1;SCLK=0;x>>=1;
}
}
//从DS1302读取一个字节
uchar Get_A_Byte_FROM_DS1302()
{
uchar i,b=0x00;
for(i=0;i<8;i++)
{
b |= _crol_((uchar)IO,i);
SCLK=1;SCLK=0;
}
return b/16*10+b%16;
}
//从DS1302指定位置读数据
uchar Read_Date(uchar addr)
{
uchar dat;
RST = 0;SCLK=0;RST=1;
Write_A_Byte_TO_DS1302(addr);
dat = Get_A_Byte_FROM_DS1302();
SCLK=1;RST=0;
return dat;
}
//读取当前日期时间
void GetDateTime()
{
uchar i,addr = 0x81;
for(i=0;i<7;i++)
{
DateTime[i]=Read_Date(addr);addr+=2;
}
}
void Format_DateTime(uchar d,uchar *a)
{
// *a=(d>>4) + '0';
// *(a+1) = (d & 0x0f) + '0';
a[0]=d/10+'0';
a[1]=d%10+'0';
}
void main()
{
Initialize_LCD();
while(1)
{
GetDateTime();
Format_DateTime(DateTime[6],LCD_BUF_1 + 5);
Format_DateTime(DateTime[4],LCD_BUF_1 + 8);
Format_DateTime(DateTime[3],LCD_BUF_1 + 11);
strcpy(LCD_BUF_1 + 13,WEEK[DateTime[5]-1]);
Format_DateTime(DateTime[2],LCD_BUF_2 + 5);
Format_DateTime(DateTime[1],LCD_BUF_2 + 8);
Format_DateTime(DateTime[0],LCD_BUF_2 + 11);
ShowString(0,0,LCD_BUF_1);
ShowString(0,1,LCD_BUF_2);
}
}
|