本帖最后由 臂力吧啦 于 2015-1-25 22:02 编辑
想利用ds1302和lcd1602做一个实时时钟,但程序不知道出了什么问题,LCD1602上显示的格式对了,但所有数字都是零。估计是DS1302部分的程序出了问题。本人新手菜鸟一枚,还望各位高手不i吝赐教!!!不胜感激!!!程序如下:
#include "STC12C5A.h"
sbit EN=P3^7; //位定义LCD1602的相关引脚
sbit RW=P3^6;
sbit RS=P3^5;
sbit SCLK=P1^3; //位定义DS1302的相关引脚
sbit IO=P3^4;
sbit RST1=P0^7;
sbit BIT0=ACC^0;
sbit BIT7=ACC^7;
unsigned char
time[]={0x00,0x40,0x23,0x24,0x01,0x05,0x15}; //初始化时间
unsigned char now[7]; //当前时间
void delay_ms(unsigned int time)
{
unsigned int t;
for(;time>0;time--)
{t=1600;while(t--);}
}
/**********DS1302部分*******************/
/***************************************/
void ds1302_input(unsigned char addr,unsigned char dat) //往ds1302写入数据
{
unsigned char i;
RST1=0;
SCLK=0;
RST1=1;
ACC=addr;
for(i=0;i<8;i++)
{
SCLK=0;
IO=BIT0;
ACC>>=1;
SCLK=1;
}
ACC=dat;
for(i=0;i<8;i++)
{
SCLK=0;
IO=BIT0;
ACC>>=1;
SCLK=1;
}
RST1=0;
}
unsigned char ds1302_output(unsigned char addr) //输出指定地址的数据
{
unsigned char i;
RST1=0;
SCLK=0;
RST1=1;
ACC=addr;
for(i=0;i<8;i++)
{
SCLK=0;
IO=BIT0;
ACC>>=1;
SCLK=1;
}
for(i=1;i<8;i++)
{
SCLK=1;
BIT7=IO;
ACC>>=1;
SCLK=0;
}
RST1=0;
return ACC;
}
void time_init(unsigned char *time) //设置初始时间
{
unsigned char addr=0x80,i;
ds1302_input(0x8e,0x00); //取消写保护
for(i=0;i<7;i++)
{
ds1302_input(addr,time
);
addr=addr+2;
}
ds1302_input(0x8e,0x80); //开启写保护
}
void get_time(unsigned char *now) //获取当前时间
{
unsigned char addr=0x81,i,t;
ds1302_input(0x8e,0x80); //开启写保护
for(i=0;i<7;i++)
{
ds1302_input(0x8e,0x00);
t=ds1302_output(addr);
ds1302_input(0x8e,0x80);
addr=addr+2;
now=(t/16)*10+(t&(0x0f));
}
}
/**********LCD1602部分*******************/
/***************************************/
void lcd_write_com(unsigned char com) //lcd1602输入命令
{
RS=0;
RW=0;
P0=com;
delay_ms(5);
EN=1;EN=0;
}
void lcd_write_dat(unsigned char dat) //lcd1602输入数据
{
RS=1;
RW=0;
P0=dat;
delay_ms(5);
EN=1;EN=0;
}
void lcd_init() //lcd1602初始化
{
lcd_write_com(0x38);
lcd_write_com(0x0c);
lcd_write_com(0x06);
lcd_write_com(0x01);
}
void show_time() //显示当前时间
{
get_time(now);
lcd_write_com(0x80);
lcd_write_dat('0'+now[6]/10);
lcd_write_dat('0'+now[6]%10);
lcd_write_dat('-');
lcd_write_com(0x83);
lcd_write_dat('0'+now[4]/10);
lcd_write_dat('0'+now[4]%10);
lcd_write_dat('-');
lcd_write_com(0x86);
lcd_write_dat('0'+now[3]/10);
lcd_write_dat('0'+now[3]%10);
lcd_write_dat(' ');
lcd_write_com(0x89);
lcd_write_dat('0'+now[5]/10);
lcd_write_dat('0'+now[5]%10);
lcd_write_com(0x80+0x40);
lcd_write_dat('0'+now[2]/10);
lcd_write_dat('0'+now[2]%10);
lcd_write_dat('-');
lcd_write_com(0x80+0x40+3);
lcd_write_dat('0'+now[1]/10);
lcd_write_dat('0'+now[1]%10);
lcd_write_dat('-');
lcd_write_com(0x80+0x40+6);
lcd_write_dat('0'+now[0]/10);
lcd_write_dat('0'+now[0]%10);
}
void main()
{
lcd_init();
time_init(time);
while(1)
{
show_time();
delay_ms(200);
}
}
单片机型号是stc12c5a60s2
一周热门 更多>