单片机数码管在定时器里的减速程序
时间: 2024-05-12 18:17:29 浏览: 14
这是一个单片机数码管在定时器里的减速程序的示例:
```c
#include <reg52.h>
#define LED P0 // 数码管连接的IO口
unsigned char code LED_CODE[] = { // 数码管显示的字符编码
0x3f,0x06,0x5b,0x4f,0x66,
0x6d,0x7d,0x07,0x7f,0x6f
};
unsigned char cnt = 0; // 计数器,用于控制显示的数字
unsigned char speed = 10; // 初始速度设为10
unsigned char timer_count = 0; // 定时器计数器,用于实现减速效果
void init_timer() {
TMOD = 0x01; // 定时器0工作在模式1
TH0 = 0xff; // 定时器初值
TL0 = 0xff;
EA = 1; // 开启总中断
ET0 = 1; // 开启定时器0中断
TR0 = 1; // 启动定时器0
}
void display() {
LED = LED_CODE[cnt]; // 显示数字
cnt++; // 计数器自增
if (cnt >= 10) cnt = 0; // 计数器归零
}
void timer0() interrupt 1 { // 定时器0中断服务程序
TH0 = 0xff; // 重新设置定时器初值
TL0 = 0xff;
timer_count++; // 计数器自增
if (timer_count == speed) { // 达到设定的速度
timer_count = 0; // 计数器归零
display(); // 显示数字
}
}
void main() {
init_timer(); // 初始化定时器
while (1) {
if (P1_0 == 0) { // 按下按钮
speed--; // 速度减1
if (speed == 0) speed = 1; // 速度最小为1
while (P1_0 == 0); // 等待按钮松开
}
}
}
```
在这个程序中,我们使用定时器0来控制数码管的显示速度。程序中定义了一个计数器`cnt`,用于控制显示的数字;一个速度变量`speed`,初始值为10;一个定时器计数器`timer_count`,用于实现减速效果。
在`init_timer()`函数中,我们将定时器0设置为模式1,初值设为0xffff,开启总中断和定时器0中断,启动定时器0。
在`display()`函数中,我们将`cnt`对应的数字显示在数码管上,并将`cnt`自增。当`cnt`超过9时,将其归零。
在定时器0中断服务程序`timer0()`中,我们重新设置定时器初值,并将`timer_count`自增。当`timer_count`等于`speed`时,说明达到了设定的速度,将`timer_count`归零,并调用`display()`函数显示数字。
在`main()`函数中,我们通过一个按键来控制速度。当按下按键时,将速度减1,并等待按键松开。当速度减到最小值1时,不再减少。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)