#include 'stick.h' #include 'led.h' #include 'beep.h'

// JOY_S->PG6 // JOY_D->PG7 // JOY_L->PG9 // JOY_R->PC4 // JOY_U->PG11

/**

  • @brief 按键初始化

  • @param void

  • @retval None */ void stick_Init() { // GPIOG RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOG, ENABLE); GPIO_InitTypeDef GPIO_InitStructure; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; // 上拉输入模式 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7 | GPIO_Pin_9 | GPIO_Pin_11; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; // 速度选择为50MHz GPIO_Init(GPIOG, &GPIO_InitStructure); GPIO_SetBits(GPIOG, GPIO_Pin_6 | GPIO_Pin_7 | GPIO_Pin_9 | GPIO_Pin_11);

    // GPIOC RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE); GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; // 上拉输入模式 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; // 速度选择为50MHz GPIO_Init(GPIOC, &GPIO_InitStructure); GPIO_SetBits(GPIOC, GPIO_Pin_4); }

/**

  • @brief 按键的捕获

  • @param void

  • @retval uint8_t 按键的键值 */ uint8_t stick_Scan() { uint8_t stick_Value = 0;

    if (GPIO_ReadInputDataBit(GPIOG, GPIO_Pin_6) == 0) { // JOY_S->PG6 stick_Value = 1; while (GPIO_ReadInputDataBit(GPIOG, GPIO_Pin_6) == 0); // 按键消抖 } else if (GPIO_ReadInputDataBit(GPIOG, GPIO_Pin_7) == 0) { // JOY_D->PG7 stick_Value = 2; while (GPIO_ReadInputDataBit(GPIOG, GPIO_Pin_7) == 0); // 按键消抖 } else if (GPIO_ReadInputDataBit(GPIOG, GPIO_Pin_9) == 0) { // JOY_L->PG9 stick_Value = 3; while (GPIO_ReadInputDataBit(GPIOG, GPIO_Pin_9) == 0); // 按键消抖 } else if (GPIO_ReadInputDataBit(GPIOC, GPIO_Pin_4) == 0) { // JOY_R->PC4 stick_Value = 4; while (GPIO_ReadInputDataBit(GPIOC, GPIO_Pin_4) == 0); // 按键消抖 } else if (GPIO_ReadInputDataBit(GPIOG, GPIO_Pin_11) == 0) { // JOY_U->PG11 stick_Value = 5; while (GPIO_ReadInputDataBit(GPIOG, GPIO_Pin_11) == 0); // 按键消抖 } return stick_Value; }

int main() { stick_Init(); led_Init_R(); beep_Init();

while (1)
{
    uint8_t stick_Value = stick_Scan();
    
    switch (stick_Value)
    {
        case 1:
            led_Red_Open(); // 按下S,亮起红灯
            break;
            
        case 2:
            led_Green_Open(); // 按下D,亮起绿灯
            break;
            
        case 3:
            led_Blue_Open(); // 按下L,亮起蓝灯
            break;
            
        case 4:
            led_White_Open(); // 按下R,亮起白灯
            break;
            
        case 5:
            beep_Open(); // 按下U,蜂鸣器响
            break;
            
        default:
            break;
    }
}
STM32按键驱动 - stick.h 文件

原文地址: https://www.cveoy.top/t/topic/EP2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录