- #include <reg52.h>
- #include <intrins.h>
- typedef unsigned char uchar;
- typedef unsigned int uint;
- sbit Max7219_pinDIN = P2^2;
- sbit Max7219_pinCS = P2^1;
- sbit Max7219_pinCLK = P2^0;
- sbit TSCLK = P1^0;
- sbit TIO = P1^1;
- sbit TRST = P1^2;
- sbit beep = P2^3;
- void delay(uint z)
- {
- uint x,y;
- for(x = z; x > 0; x--)
- for(y = 114; y > 0 ; y--);
- }
- void Write_Max7219_byte(uchar DATA)
- {
- uchar i;
- for(i=8;i>=1;i--)
- {
- Max7219_pinCLK=0;
- Max7219_pinDIN=DATA&0x80;
- DATA=DATA<<1;
- Max7219_pinCLK=1;
- }
- }
- void Write_Max7219(uchar address,uchar dat)
- {
- Max7219_pinCS=0;
- Write_Max7219_byte(address); //写入地址,即数码管编号
- Write_Max7219_byte(dat); //写入数据,即数码管显示数字
- Max7219_pinCS=1;
- }
- void Init_MAX7219(void)
- {
- Write_Max7219(0x09, 0xff); //译码方式:BCD码
- Write_Max7219(0x0a, 0x03); //亮度
- Write_Max7219(0x0b, 0x07); //扫描界限;4个数码管显示
- Write_Max7219(0x0c, 0x01); //掉电模式:0,普通模式:1
- Write_Max7219(0x0f, 0x01); //显示测试:1;测试结束,正常显示:0
- }
- void display(uchar hour, uchar min, uchar sec )
- {
- uchar hour1, hour2, min1, min2, sec1, sec2;
- hour1 = hour / 10 % 10;
- hour2 = hour % 10;
- min1 = min / 10 % 10;
- min2 = min % 10;
- sec1 = sec / 10 % 10;
- sec2 = sec % 10;
- Write_Max7219(1,sec2);
- Write_Max7219(2,sec1);
- Write_Max7219(3,0x0A); //显示-
- Write_Max7219(4,min2);
- Write_Max7219(5,min1);
- Write_Max7219(6,0x0A);
- Write_Max7219(7,hour2);
- Write_Max7219(8,hour1);
- }
- //写DS1302数据
- void Write_DS1302_Data(uchar cmd, uchar dat)
- {
- uchar i;
- TRST = 0;
- TSCLK = 0;
- TRST = 1;
- for(i=0;i<8;i++)
- {
- TSCLK = 0;
- TIO = cmd & 0x01; //从低到高写数据
- TSCLK = 1;
- cmd >>= 1;
- }
- for(i=0;i<8;i++)
- {
- TSCLK = 0;
- TIO = dat & 0x01;
- TSCLK = 1;
- dat >>= 1;
- }
- }
- //读DS1302数据
- uchar Read_DS1302_Data(uchar cmd)
- {
- uchar i, dat;
- TRST = 0;
- TSCLK = 0;
- TRST = 1;
- for(i=0;i<8;i++)
- {
- TSCLK = 0;
- TIO = cmd & 0x01;
- TSCLK = 1;
- cmd >>= 1;
- }
- for(i=0;i<8;i++)
- {
- TSCLK = 0;
- dat >>= 1;
- if(TIO) dat |= 0x80;
- TSCLK = 1;
- }
- return dat;
- }
- uchar BCD_Chg_Data(uchar dat)
- {
- uchar dat1, dat2;
- dat1 = dat / 16;
- dat2 = dat % 16;
- dat2 = dat2 + dat1*10;
- return dat2;
- }
- void Init_DS1302()
- {
- Write_DS1302_Data(0x8e, 0); //清除写保护
- Write_DS1302_Data(0x80, 0x50); //秒
- Write_DS1302_Data(0x82, 0x59); //分
- Write_DS1302_Data(0x84, 0x23); //时
- Write_DS1302_Data(0x8e, 0x80); //打开写保护
- }
- void main()
- {
- uchar sec, min, hour;
- Init_MAX7219();
- delay(1000);
- Write_Max7219(0x0f, 0x00);
- Init_DS1302();
- while(1)
- {
- Write_DS1302_Data(0x8e, 0);
- sec = BCD_Chg_Data(Read_DS1302_Data(0x81)); //读寄存器
- min = BCD_Chg_Data(Read_DS1302_Data(0x83));
- hour = BCD_Chg_Data(Read_DS1302_Data(0x85));
- Write_DS1302_Data(0x8e, 0x80);
- display(hour, min, sec);
- if(hour==0 && min==0 && sec==0)
- {
- beep = 0;
- delay(1000);
- beep = 1;
- }
- }
- }
复制代码 |