188数码管stm32
时间: 2023-10-28 11:19:04 浏览: 244
数码管显示_stm32数码管显示_
5星 · 资源好评率100%
STM32是一款基于ARM Cortex-M处理器的微控制器,可以通过STM32的GPIO口控制数码管的显示。对于188数码管,可以使用8个GPIO口分别控制其8个数码管的显示。
具体实现过程如下:
1. 确定使用的GPIO口,例如PA0~PA7口。
2. 配置GPIO口为输出模式。
3. 使用循环控制每个数码管的显示,每次循环控制一个数码管的显示,同时控制该数码管对应的GPIO口输出高电平,其他GPIO口输出低电平。
4. 根据需要的数字,使用数组或switch语句确定每个数码管需要显示的数字。
5. 使用定时器控制数码管的刷新频率,防止闪烁。
示例代码如下:
```
#include "stm32f10x.h"
//定义8个GPIO口,用于控制8个数码管的显示
#define GPIOA_0 GPIO_Pin_0
#define GPIOA_1 GPIO_Pin_1
#define GPIOA_2 GPIO_Pin_2
#define GPIOA_3 GPIO_Pin_3
#define GPIOA_4 GPIO_Pin_4
#define GPIOA_5 GPIO_Pin_5
#define GPIOA_6 GPIO_Pin_6
#define GPIOA_7 GPIO_Pin_7
//定义数字0~9在数码管上的显示对应的GPIO口状态
uint16_t num[10] = {
GPIOA_0 | GPIOA_1 | GPIOA_2 | GPIOA_4 | GPIOA_5 | GPIOA_6, //0
GPIOA_2 | GPIOA_5, //1
GPIOA_0 | GPIOA_2 | GPIOA_3 | GPIOA_4 | GPIOA_6, //2
GPIOA_0 | GPIOA_2 | GPIOA_3 | GPIOA_5 | GPIOA_6, //3
GPIOA_1 | GPIOA_2 | GPIOA_3 | GPIOA_5, //4
GPIOA_0 | GPIOA_1 | GPIOA_3 | GPIOA_5 | GPIOA_6, //5
GPIOA_0 | GPIOA_1 | GPIOA_3 | GPIOA_4 | GPIOA_5 | GPIOA_6, //6
GPIOA_0 | GPIOA_2 | GPIOA_5, //7
GPIOA_0 | GPIOA_1 | GPIOA_2 | GPIOA_3 | GPIOA_4 | GPIOA_5 | GPIOA_6, //8
GPIOA_0 | GPIOA_1 | GPIOA_2 | GPIOA_3 | GPIOA_5 | GPIOA_6 //9
};
int main(void)
{
//初始化GPIO口为输出模式
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIOA_0 | GPIOA_1 | GPIOA_2 | GPIOA_3 | GPIOA_4 | GPIOA_5 | GPIOA_6 | GPIOA_7;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
//初始化定时器,控制数码管的刷新频率
TIM_TimeBaseInitTypeDef TIM_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_InitStructure.TIM_Period = 1000; //定时器周期为1ms
TIM_InitStructure.TIM_Prescaler = 72 - 1; //时钟预分频为72
TIM_InitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_InitStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_InitStructure);
TIM_Cmd(TIM2, ENABLE);
uint8_t disp[8] = {0}; //用于存储每个数码管需要显示的数字
uint32_t time_cnt = 0; //用于计数定时器溢出的次数,控制数码管的刷新
while (1)
{
//根据需要显示的数字,设置每个数码管的显示状态
disp[0] = 1;
disp[1] = 8;
disp[2] = 8;
disp[3] = 1;
disp[4] = 8;
disp[5] = 8;
disp[6] = 1;
disp[7] = 0;
//循环控制每个数码管的显示
for (uint8_t i = 0; i < 8; i++)
{
//控制当前数码管对应的GPIO口输出高电平,其他GPIO口输出低电平
GPIO_SetBits(GPIOA, GPIOA_0 | GPIOA_1 | GPIOA_2 | GPIOA_3 | GPIOA_4 | GPIOA_5 | GPIOA_6 | GPIOA_7);
GPIO_ResetBits(GPIOA, 1 << i);
//根据需要显示的数字设置当前数码管的显示状态
GPIO_SetBits(GPIOA, num[disp[i]]);
//等待一段时间,防止闪烁
for (uint32_t j = 0; j < 100; j++);
}
//等待定时器溢出,控制数码管的刷新频率
while (TIM_GetFlagStatus(TIM2, TIM_FLAG_Update) == RESET);
TIM_ClearFlag(TIM2, TIM_FLAG_Update);
time_cnt++;
}
}
```
阅读全文