#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); } } } }
|