keil5 stm32为什么这个程序只按加数据Key_GetNum() == 3有用,按另一个按键Key_GetNum() == 4减不了数据


int main(void)
{
    LED_Init();
    DHT11_Init();
    OLED_Init();
    Key_Init();
    CountSensor_Init();
    Adc_Init();    
    LED1_ON();
    Buzzer_Init();
    uart_init(115200);
     
    while (1)
    {
    Show_sz();
    }
    
}

void Show_sz(void)
{
     OLED_ShowString(1, 1, "tempH:");
     OLED_ShowString(1, 12, "L:");
     OLED_ShowString(2, 1, "humiH:");
     OLED_ShowString(2, 12, "L:");
     OLED_ShowString(3, 1, "smogH:");
   OLED_ShowNum(1, 7, temp_max,2);
      OLED_ShowNum(1, 15, temp_min,2);
     OLED_ShowNum(2, 7, humi_max,2);
      OLED_ShowNum(2, 15, humi_min,2);
     OLED_ShowNum(3, 7, s,4);
         if(Key_GetNum() == 3)
        {        
        
              switch(cursor)
           {
              case 0:temp_max++;break;
              case 1:temp_min++;break;
                    case 2:humi_max++;break; 
                  case 3:humi_min++;break;
                 }            
            }
             if(Key_GetNum() == 4)
         {        
        
              switch(cursor)
           {
              case 0:temp_max--;break;
              case 1:temp_min--;break;
                    case 2:humi_max--;break; 
                  case 3:humi_min--;break;
                 }            
            }

}

uint8_t Key_GetNum(void)
{
    uint8_t KeyNum = 0;
    if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_4) == 0)
    {
        Delay_ms(5);
        if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_4) == 0)
        {
         while (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_4) == 0);
         Delay_ms(5);
         KeyNum = 1;
        }
    }
    if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_5) == 0)
    {
        Delay_ms(5);
        if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_5) == 0)
        {
         while (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_5) == 0);
         Delay_ms(5);
         KeyNum = 2;
        }
    }
    if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_6) == 0)
    {
        Delay_ms(5);
        if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_6) == 0)
        {
         while (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_6) == 0);
         Delay_ms(5);
         KeyNum = 3;
        }
    }
    if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_7) == 0)
    {
        Delay_ms(5);
        if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_7) == 0)
        {
         while (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_7) == 0);
         Delay_ms(5);
         KeyNum = 4;
        }
    }
    return KeyNum;
}

看叉了,不好意思。这个问题可能是因为按键的抖动造成的。在按下按键时,由于机械开关的特性,会产生多次开关状态的变化,导致程序判断按键状态时出现误判。可以尝试增加延时时间或者添加消抖程序来解决这个问题。还有,看看按键的引脚和程序中定义的引脚是不是一致的,最后一种可能就是板子的按键有问题

调试一下,看看是键盘的故障,还是你的程序的问题