#include <stm32f10x.h>
#define _BV(n) (1 << (n))
uint8_t segdisp[] = {0xc0, 0xf9, 0xa4, 0xb0, 0x99, 0x92, 0x82, 0xf8, 0x80, 0x90};
uint16_t nNumber = 2016;
#define K1 GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_0)
#define K2 GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_1)
void delay()
{
uint32_t i;
for (i = 0; i < 20000; i++);
}
// 数码管动态扫描函数
// n为扫描次数
void scan_7seg(uint8_t n)
{
uint8_t i;
uint16_t nTemp;
while (n--)
{
nTemp = nNumber;
for (i = 7; i >= 4; i--) // i表示要显示的数码管
{
GPIO_Write(GPIOA, ~_BV(i));
GPIO_Write(GPIOB, ~segdisp[nTemp % 10] << 8);
delay();
nTemp /= 10;
}
}
}
int main(void)
{
GPIO_InitTypeDef init;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB, ENABLE);
// PA设置为输出
init.GPIO_Pin = GPIO_Pin_All;
init.GPIO_Speed = GPIO_Speed_50MHz;
init.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOA, &init);
// PB8~15设置为输出
init.GPIO_Pin = 0xff00;
GPIO_Init(GPIOB, &init);
// PB0~7设置为输入
init.GPIO_Pin = 0x00ff;
init.GPIO_Mode = GPIO_Mode_IPD;
GPIO_Init(GPIOB, &init);
while (1)
{
/* 显示数字 */
scan_7seg(1);
/* 按键检测 */
// 按键1使数字减小
if (!K1) // 按键按下时为低电平
{
scan_7seg(4); // 把按键消抖程序中所有的延时函数改为数码管扫描函数, 防止数码管闪烁或熄灭
if (!K1)
{
if (nNumber > 0)
nNumber--;
else
nNumber = 9999;
while (!K1)
scan_7seg(1);
}
}
// 按键2使数字增大
if (!K2)
{
scan_7seg(4);
if (!K2)
{
nNumber++;
if (nNumber >= 10000)
nNumber = 0;
while (!K2)
scan_7seg(1);
}
}
}
}