最近在接受51单片机培训,并且要完成一个课设。基于老师今天讲的定时器和前天讲的数码管的知识,迸发出灵感设计了一个计时器,开机即从0s开始计时,一直到60h,此时 h min s 三个时间都归零并重新计时(设置什么样的归零时间看自己需求),由于我只是对于c代码的使用较熟练一些,这里就不写硬件以及原理知识,日后神功大成再来补充。
废话不多说,放代码!
(注意:这里使用的是多模块编程哦。)
main.c
#include <reg51.h>
#include <intrins.h>
#include "mydelay.h"
#include "variable.h" // 包含全局变量的头文件
#define uchar unsigned char
#define uint unsigned int
uchar i = 0;
uchar hour = 0;
uchar minute = 0;
uchar second = 0;
void display();
void main()
{
//定时器0的中断允许位
ET0 = 1;
EA = 1;
TMOD = 0x01;
TH0 = (65535 - 50000) / 256;
TL0 = (65536 - 50000) % 256;
//打开定时器
TR0 = 1;
while(1)
{
//数码管的显示
display();
}
}
mydelay.c
#include "mydelay.h"
void delay(unsigned int ms)
{
//circulation for
unsigned int i,j;
for(i = ms;i>0;i--)
{
for(j = 110;j>0;j--);
}
}
mydelay.h
#ifndef _mydelay_h_
#define _mydelay_h_
void delay(unsigned int ms);
#endif
timer0.c
#include <reg51.h>
#include "variable.h" // 包含全局变量的头文件
#define uchar unsigned char
//当计时50ms收到定时器中断的信号后,会执行下面的函数
void Timer0() interrupt 1
{
//定时器中断的处理代码
i++;
if(i == 20)
{
//经过了1s
i = 0;
second++;
}
if(second==60)
{
second = 0;
minute++;
}
if(minute == 60)
{
minute = 0;
hour++;
}
if(hour == 60)
{
second =0;
minute=0;
hour=0;
}
//每次计时完都需要重新装载初值
TH0 = (65535 - 50000) / 256;
TL0 = (65536 - 50000) % 256;
}
display.c
#include <reg51.h>
#define uchar unsigned char
#include "mydelay.h"
#include "variable.h" // 包含全局变量的头文件
uchar code tab[11] = {0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F};//0 1,2,3,4,5,6,7,8,9
//功能:使用数码管显示当前的时间
void display()
{
//second
P2 = 0xe3; //最右侧数码管亮
P0 = tab[second%10];
delay(1);
//消影
P0 = 0x00;
delay(1);
P2 = 0xe7;
P0 = tab[second/10];
delay(1);
//消影
P0 = 0x00;
delay(1);
//-
P2 = 0xeb;
P0 = 0x40;
delay(1);
//消影
P0 = 0x00;
delay(1);
//minute
P2 = 0xef;
P0 = tab[minute%10];
delay(1);
//消影
P0 = 0x00;
delay(1);
P2 = 0xf3;
P0 = tab[minute/10];
delay(1);
//消影
P0 = 0x00;
delay(1);
//-
P2 = 0xf7;
P0 = 0x40;
delay(1);
//消影
P0 = 0x00;
delay(1);
//hour
P2 = 0xfb;
P0 = tab[hour%10];
delay(1);
//消影
P0 = 0x00;
delay(1);
P2 = 0xff;//最左侧数码管
P0 = tab[hour/10];
delay(1);
//消影
P0 = 0x00;
delay(1);
}
variable.h
#ifndef _variable_H
#define _vaariable_H
#define uchar unsigned char
extern uchar i; // 记录定时中断触发的次数
extern uchar hour;
extern uchar minute;
extern uchar second;
#endif
标签:P0,uchar,51,unsigned,delay,单片机,include,minute
From: https://blog.csdn.net/z1614243296/article/details/144973161