[Embedded system experiment] 3 key input experiment

1 Development environment

  • STM32F407ZGT6
  • Wedge uVision 5

2 Experiment content

  • Modify the program
  1. After pressing KEY0, the brightness of LED0 changes from bright to dark, and then from dark to bright (breathing light effect). When LED0 is on, there is no extinguishment or pause.
  2. After pressing KEY1, LED0 goes out.
  • No pwm

3 Experimental code

[main.c]

int main(void)
{
    
     
 
	u8 key;           	//保存键值
	delay_init(168);  	//初始化延时函数
	LED_Init();			//初始化LED端口 
	BEEP_Init();      	//初始化蜂鸣器端口
	KEY_Init();       	//初始化与按键连接的硬件接口
	LED0=0;				//先点亮红灯
	
	while(1){
    
    
		key=KEY_Scan(0);				//扫描按键
		if(key){
    
    						//若有按键
			switch(key){
    
    
				case WKUP_PRES:
				case KEY2_PRES:
					break;
				case KEY1_PRES:			//按下KEY1
					LED0=1;				//熄灭LED0
					break;
				case KEY0_PRES:
					while(1){
    
    
						int flag=0;
						int i;
						int breath_total=1500;						//整个周期,ms
						int breath_eyes=20;							//人眼可见无跳闪的周期,ms
						int breath_cyc=breath_total/breath_eyes;	//小时间片

						for(i=breath_cyc;i>=5;i-=1){
    
    				//从亮到暗
							if(KEY_Scan(1)==KEY1_PRES){
    
    				//若按下KEY1
								flag=1;								//灭灯立flag
								LED0=1;
								break;								//跳出for循环
							}
							led_breath(breath_eyes,breath_eyes*i/breath_cyc);	//呼吸灯闪烁
						}//for(i=breath_cyc;i>=5;i-=1)
						
						for(i=5;i<=breath_cyc;i++){
    
    					//从暗到亮
							if(KEY_Scan(1)==KEY1_PRES){
    
    				//若按下KEY1
								flag=1;								//灭灯立flag
								LED0=1;
								break;								//跳出for循环
							}
							led_breath(breath_eyes,breath_eyes*i/breath_cyc);	//呼吸灯闪烁
						}//for(i=5;i<=breath_cyc;i++)
						
						if(KEY_Scan(1)==KEY1_PRES||flag){
    
    			//若按下KEY1或flag已立下
							LED0=1;									//灭灯
							break;									//跳出wile循环
						}
					}//while(1)
					break;
			}//switch(key)
		}//if(key)
	}//while(1)
}
/*呼吸灯闪烁*/
void led_breath(u32 t,u32 bright){
    
    
	delay_ms(bright);
	LED0=1;
	delay_ms(t-bright);
	LED0=0;
}

Guess you like

Origin blog.csdn.net/qq_44714521/article/details/108704149