目前共有1篇帖子。 內容轉換:不轉換▼
 
點擊 回復
228 0
【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);
            }
        }
    }
}

回復帖子

內容:
用戶名: 您目前是匿名發表
驗證碼:
(快捷鍵:Ctrl+Enter)
 

本帖信息

點擊數:228 回複數:0
評論數: ?
作者: 巨大八爪鱼
最後回復:巨大八爪鱼
最後回復時間:2016-5-14 19:32
 
©2010-2024 Arslanbar Ver2.0
除非另有聲明,本站採用創用CC姓名標示-相同方式分享 3.0 Unported許可協議進行許可。