設置 | 登錄 | 註冊

目前共有1篇帖子。

【STM32入門級程序8】使用庫函數實現按鍵控制數碼管

1樓 巨大八爪鱼 2016-5-14 19:32
#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);
            }
        }
    }
}

內容轉換:

回覆帖子
內容:
用戶名: 您目前是匿名發表。
驗證碼:
看不清?換一張
©2010-2025 Purasbar Ver3.0 [手機版] [桌面版]
除非另有聲明,本站採用知識共享署名-相同方式共享 3.0 Unported許可協議進行許可。