stm32 2位数码管动态显示实现30秒倒计时
时间: 2023-06-20 12:05:18 浏览: 171
以下是使用STM32动态显示2位数码管实现30秒倒计时的简单代码实现:
```c
#include "stm32f10x.h"
// 定义数码管引脚
#define SEG_A GPIO_Pin_0
#define SEG_B GPIO_Pin_1
#define SEG_C GPIO_Pin_2
#define SEG_D GPIO_Pin_3
#define SEG_E GPIO_Pin_4
#define SEG_F GPIO_Pin_5
#define SEG_G GPIO_Pin_6
#define SEG_DP GPIO_Pin_7
// 定义数码管显存
uint8_t segTab[] = {0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f};
// 定义数码管位选引脚
#define DIGIT_0 GPIO_Pin_8
#define DIGIT_1 GPIO_Pin_9
// 定义30秒倒计时时间
#define COUNT_DOWN_TIME 30
// 延时函数
void delay(uint32_t nCount)
{
for(; nCount != 0; nCount--);
}
// 数码管显示函数
void display(uint8_t num)
{
GPIO_Write(GPIOB, segTab[num % 10]);
GPIO_SetBits(GPIOA, DIGIT_0);
delay(1000);
GPIO_ResetBits(GPIOA, DIGIT_0);
GPIO_Write(GPIOB, segTab[num / 10]);
GPIO_SetBits(GPIOA, DIGIT_1);
delay(1000);
GPIO_ResetBits(GPIOA, DIGIT_1);
}
int main(void)
{
uint8_t countDown = COUNT_DOWN_TIME;
// 初始化GPIO口
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = SEG_A | SEG_B | SEG_C | SEG_D | SEG_E | SEG_F | SEG_G | SEG_DP;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = DIGIT_0 | DIGIT_1;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// 开始倒计时
while(countDown--)
{
display(countDown);
}
// 显示结束
GPIO_Write(GPIOB, segTab[0]);
GPIO_SetBits(GPIOA, DIGIT_0);
GPIO_SetBits(GPIOA, DIGIT_1);
while(1);
}
```
注意事项:
- 本代码使用的是STM32F103C8T6开发板,使用其他型号的开发板可能需要修改代码中的GPIO引脚、定时器等相关配置。
- 本代码使用的是共阳数码管,如果使用共阴数码管需要修改`segTab`表中的数码管段码。
- 本代码中的延时函数是通过空循环实现的,不够精确,实际项目中应该使用定时器实现更精确的延时。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)