在51单片机实验板上,用C语言编程实现秒表计时器的设计。51单片机外接晶振频率为12MHz,使用单片机定时/计数器的工作方式1产生周期为50ms的方波。 1.该秒表计时器在0~59秒范围内循环计时,每次增加1秒。 2.当复位键有效时,该计时器清零后不再计时。 3.在复位键无效的前提下,当使能键有效时该计时器开始计时,当使能键无效时该计时器暂停计时。 4.使用两位数码管动态显示计时值。
时间: 2023-05-19 08:01:49 浏览: 169
以下是实现秒表计时器的C语言代码:
#include <reg51.h>
#define uchar unsigned char
#define uint unsigned int
sbit KEY1 = P3^0; // 复位键
sbit KEY2 = P3^1; // 使能键
sbit DIO = P2^0; // 数码管数据线
sbit CLK = P2^1; // 数码管时钟线
uchar code table[] = { // 数码管显示表
0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07,
0x7f, 0x6f, 0x77, 0x7c, 0x39, 0x5e, 0x79, 0x71
};
uchar second = 0; // 秒数
bit enable = 0; // 使能标志
void delay(uint t) { // 延时函数
uint i, j;
for (i = t; i > 0; i--)
for (j = 110; j > 0; j--);
}
void display(uchar num) { // 数码管显示函数
uchar i;
for (i = 0; i < 8; i++) {
DIO = (table[num] >> i) & 0x01;
CLK = 1;
CLK = 0;
}
}
void timer0() interrupt 1 { // 定时器0中断服务函数
TH0 = (65536 - 50000) / 256; // 50ms
TL0 = (65536 - 50000) % 256;
if (enable) {
second++;
if (second >= 60)
second = 0;
}
}
void main() {
uchar cnt = 0;
TMOD = 0x01; // 定时器0工作方式1
TH0 = (65536 - 50000) / 256; // 50ms
TL0 = (65536 - 50000) % 256;
TR0 = 1; // 启动定时器0
ET0 = 1; // 允许定时器0中断
EA = 1; // 允许总中断
while (1) {
if (!KEY1) { // 复位键按下
enable = 0;
second = 0;
display(0);
delay(1000);
}
if (!KEY2) // 使能键按下
enable = 1;
if (enable) {
display(second / 10); // 显示十位
delay(5);
display(second % 10); // 显示个位
delay(5);
}
else {
display(16); // 显示-
delay(10);
display(16);
delay(10);
}
}
}
该代码使用定时器0产生50ms的中断,每次中断时秒数加1,当秒数达到60时清零。复位键按下时清零秒数并暂停计时,使能键按下时开始计时,否则暂停计时。使用两位数码管动态显示计时值。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)