"Blue Bridge Cup Preparation" STM32GPIO library function GPIO_ReadInputDataBit ()

insert image description here
In addition to the commonly used
GPIO_ResetBits(GPIOx ,GPIO_Pin_x);
GPIO_SetBits(GPIOx ,GPIO_Pin_x);

Focus on the library function GPIO_ReadInputDataBit(), refer to the
STM32 firmware library manual to
insert image description here
write the button driver, there are two main ways, the specific problems are analyzed in detail

(1) Cyclic scan
(2) External interrupt

Using the cyclic scanning method, you need to continuously detect the state of the key, that is, the state of a GPIO pin related to the key. You can use the GPIO_ReadInputDataBit() library function to detect in while(1), and the result of GPIO_ReadInputDataBit() is assigned to a variable, and then judge the value of the variable.

Part of the program description :
PA0State variable---->PA0 (KEY1) state
Delay_ms (100) uses software to debounce
Led_Control () itself encapsulates the GPIO library function to set the level function

/*程序功能:LED实现的效果是KEY1一直按下LED一直亮,直到K1松开LED熄灭*/
int main()
{
    
    
	
  Led_Init();
  Key_Init();
  Led_Control(0,LED_ALL);

  while(1){
    
    
	uint32_t PA0State = GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0);
		
   if(PA0State==0)
{
    
        
	 Delay_ms(100);
	 if(PA0State==0) Led_Control(1,LED1);
}

   else if(PA0State==1)
	{
    
    
		Delay_ms(100);
	  if(PA0State==1) Led_Control(0,LED1);
	}
}
}
void Led_Control(uint8_t State,uint16_t LEDx)
{
    
    
	
	if(State==1)
	{
    
    
	GPIO_ResetBits(GPIOC, LEDx);
		
	/*蓝桥杯开发板上74HC573作为数据锁存器,所以每次操作需要给PD一个下降沿*/
	GPIO_SetBits(GPIOD, GPIO_Pin_2);
	GPIO_ResetBits(GPIOD, GPIO_Pin_2);
	}
	else if(State==0)
	{
    
    
		GPIO_SetBits(GPIOC, LEDx);
	    GPIO_SetBits(GPIOD, GPIO_Pin_2);
	    GPIO_ResetBits(GPIOD, GPIO_Pin_2);
	}
}

Common requirements of key-controlled LED:
1. The effect of LED is that K1 keeps pressing the LED and keeps on, until K1 is released, the LED goes out
2. Press K1 to make the LED bright, and then press to turn the LED off, and so on!

/*程序功能:按一下K1实现LED亮,再按一下实现LED灭,如此反复!*/
int pre=1;
int main()
{
    
    
	
  Led_Init();
  Key_Init();
  Led_Control(0,LED_ALL);
  
  while(1){
    
    
		
	uint32_t PA0State = GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0);
		
   if(PA0State==0 && pre==1) 
{
    
        
	      Delay_ms(400);
	    if(PA0State==0)
		  {
    
     Led_Control(1,LED1);
		         pre=0;}
}

  else if(PA0State==0&&pre==0)
	{
    
    
		    Delay_ms(400);
	     if(PA0State==0)
			{
    
     Led_Control(0,LED1);
				pre=1;}
	}

	}
}

Guess you like

Origin blog.csdn.net/Eterlove/article/details/122499952