stm32按键的检测(EXTI和Polling两种方式)

好像很简单的,但...


EXTI Mode时,只要别漏下面这两行基本是没问题了.

RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);    /* 复用时钟使能 */

GPIO_EXTILineConfig(GPIO_PortSourceGPIOB,GPIO_PinSource1); /* 选择GPIO管脚用作外部中断线路 */


#include
#include


#define EXTI_Trigger_Mode


#define KEY_RCC RCC_APB2Periph_GPIOB
#define KEY_GPIO GPIOB
#define KEY_PIN (GPIO_Pin_1)
#define KEY_LINE (EXTI_Line1)


#ifdef EXTI_Trigger_Mode
void rt_hw_key_gpio_init(void);
void rt_hw_key_exti_init(void);
void rt_hw_key_navi_init(void);
#else
void rt_key_polling_judge(void);
#endif

以上是.h文件内容


#include "key.h"


void rt_hw_key_gpio_init(void)
{
    GPIO_InitTypeDef GPIO_InitStructure;
    RCC_APB2PeriphClockCmd(KEY_RCC, ENABLE); 
    GPIO_InitStructure.GPIO_Pin = KEY_PIN;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
    GPIO_Init(KEY_GPIO,&GPIO_InitStructure);
}


#ifdef EXTI_Trigger_Mode
void rt_hw_key_exti_init(void)
{
    EXTI_InitTypeDef EXTI_InitStructure; 
    EXTI_InitStructure.EXTI_Line = KEY_LINE; 
    EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; 
    EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising; 
    EXTI_InitStructure.EXTI_LineCmd = ENABLE; 
    EXTI_Init(&EXTI_InitStructure); 
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE); 
    GPIO_EXTILineConfig(GPIO_PortSourceGPIOB,GPIO_PinSource1);
}


void rt_hw_key_navi_init(void)
{
    NVIC_InitTypeDef NVIC_InitStructure; 
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);  
    NVIC_InitStructure.NVIC_IRQChannel = EXTI1_IRQn; 
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; 
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2; 
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; 
    NVIC_Init(&NVIC_InitStructure);
}


void EXTI1_IRQHandler(void)
{
    if(EXTI_GetITStatus(KEY_LINE) == SET)
    {
        rt_kprintf("~~~~~~~~~~~~~~~~~~~~~~~~~~111~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n");
        EXTI_ClearFlag(KEY_LINE); 
    }
}
#else
void rt_key_polling_judge(void)
{
    while(1)
    {
        if(GPIO_ReadInputDataBit(KEY_GPIO,KEY_PIN) == 0)
        {
            rt_thread_delay(100);
            if(GPIO_ReadInputDataBit(KEY_GPIO,KEY_PIN) == 0)
            {
                rt_kprintf("~~~~~~~~~~~~~~~~~~~~~~~~~~222~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n");
            }
        }
    }
}
#endif


以上是.c的内容.

你可能感兴趣的:(RT-thread,STM32)