main.c文件中
#include <STC15F2K60S2.H>
#include "ds1302.h"
sbit HC138_A=P2^5;
sbit HC138_B=P2^6;
sbit HC138_C=P2^7;
sbit buzz_1= P0^6;
sbit jdq_2= P0^4;
extern unsigned char hour,min,s;// 引用
unsigned char code SMG_duanma[18]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x88,0x80,0xc6,0xc0,0x86,0x8e,0xbf,0x7f};//有第零个位置
void DelaySMG(unsigned int num)
{
unsigned int i;
while(num--)
for(i=0; i<628; i++);
}
void Init_HC138(unsigned char n)
{
switch (n)
{
case 4:
HC138_A=0;
HC138_B=0;
HC138_C=1;
break;
case 5:
HC138_A=1;
HC138_B=0;
HC138_C=1;
break;
case 6:
HC138_A=0;
HC138_B=1;
HC138_C=1;
break;
case 7:
HC138_A=1;
HC138_B=1;
HC138_C=1;
break;
}
}
void close_buzz()
{
Init_HC138(5);
buzz_1=0;//0是关闭
jdq_2=0;//0是关闭
}
void led_disp()
{
Init_HC138(4);
P0=0xf0;
}
void smg_show_bit(unsigned char dat,unsigned char pos)
{
Init_HC138(6);//数码管的位置
P0=0x01<<pos;
Init_HC138(7);//数码管的内容
P0=dat;
}
void SMG_Display()
{
smg_show_bit(SMG_duanma[hour/16],0);
DelaySMG(2) ;
smg_show_bit(SMG_duanma[hour%16],1);
DelaySMG(2) ;
smg_show_bit(SMG_duanma[16],2);
DelaySMG(2) ;
smg_show_bit(SMG_duanma[min/16],3);
DelaySMG(2) ;
smg_show_bit(SMG_duanma[min%16],4);
DelaySMG(2) ;
smg_show_bit(SMG_duanma[16],5);
DelaySMG(2) ;
smg_show_bit(SMG_duanma[s/16],6);
DelaySMG(2) ;
smg_show_bit(SMG_duanma[s%16],7);
DelaySMG(2) ;
}
void main()
{
close_buzz();
led_disp();
Ds1302_init(0x13,0x51,0x10);
while(1)
{
Ds1302_read();
SMG_Display();
}
}
ds1302.h中
#ifndef __DS1302_H
#define __DS1302_H
#include <STC15F2K60S2.H>
#include <intrins.h>
sbit SCK = P1^7;
sbit SDA = P2^3;
sbit RST = P1^3;
void Write_Ds1302(unsigned char temp);
void Write_Ds1302_Byte( unsigned char address,unsigned char dat );
unsigned char Read_Ds1302_Byte( unsigned char address );
void Ds1302_init(unsigned char h,m,s);
void Ds1302_read();
#endif
ds1302.c中
#include "ds1302.h"
unsigned char hour=0,min=0,s=0;// 小时分钟秒
//写字节
void Write_Ds1302(unsigned char temp)
{
unsigned char i;
for (i=0;i<8;i++)
{
SCK = 0;
SDA = temp&0x01;
temp>>=1;
SCK=1;
}
}
//向DS1302寄存器写入数据
void Write_Ds1302_Byte( unsigned char address,unsigned char dat )
{
RST=0; _nop_();
SCK=0; _nop_();
RST=1; _nop_();
Write_Ds1302(address);
Write_Ds1302(dat);
RST=0;
}
//从DS1302寄存器读出数据
unsigned char Read_Ds1302_Byte ( unsigned char address )
{
unsigned char i,temp=0x00;
RST=0; _nop_();
SCK=0; _nop_();
RST=1; _nop_();
Write_Ds1302(address);
for (i=0;i<8;i++)
{
SCK=0;
temp>>=1;
if(SDA)
temp|=0x80;
SCK=1;
}
RST=0; _nop_();
SCK=0; _nop_();
SCK=1; _nop_();
SDA=0; _nop_();
SDA=1; _nop_();
return (temp);
}
void Ds1302_init(unsigned char h,m,s)
{
Write_Ds1302_Byte(0x84,h);
Write_Ds1302_Byte(0x82,m);
Write_Ds1302_Byte(0x80,s);
}
void Ds1302_read()
{
hour=Read_Ds1302_Byte (0x85);
min =Read_Ds1302_Byte (0x83);
s =Read_Ds1302_Byte (0x81);
}