两个按键分别控制两盏LED灯

一、控制电路

1、LED分别接入PA1和PA2引脚,为低电平点亮。

2、按键分别接入PB1和PB11。

二、按键程序

1、按键GPIO外设初始化

void Key_Init(void)
{
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
	GPIO_InitTypeDef GPIO_Sturuct;
	GPIO_Sturuct.GPIO_Mode = GPIO_Mode_IPU;//设置为上拉输入模式
	GPIO_Sturuct.GPIO_Pin = GPIO_Pin_1 | GPIO_Pin_11;
	GPIO_Sturuct.GPIO_Speed = GPIO_Speed_50MHz;
	
	GPIO_Init(GPIOB, &GPIO_Sturuct);

}

2、按键检测程序 

 2、按键按下时为低电平,通过GPIO_ReadInputDataBit()函数读取按键状态,定义Key_GetNum()函数,当检测到按键按下时将KeyNum变量置1,返回KeyNum的值。

uint8_t Key_GetNum(void)
{
		uint8_t KeyNum = 0;
		if(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_1) == 0) 
		{
				Delay_ms(20); //延时消除抖动
				while(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_1) == 0)
				Delay_ms(20);	
				KeyNum = 1;
		}
		
			if(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_11) == 0) 
		{
				Delay_ms(20);
				while(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_11) == 0)
				Delay_ms(20);	
				KeyNum = 2;
		}
		
		
		return KeyNum;
}

 

三、GPIO初始化

1、LED灯GPIO初始化

定义LED_Init()函数,对LED灯的GPIO外设进行初始化。

void LED_Init(void)
{
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
	GPIO_InitTypeDef GPIO_Sturuct;
	GPIO_Sturuct.GPIO_Mode = GPIO_Mode_Out_PP;
	GPIO_Sturuct.GPIO_Pin = GPIO_Pin_1 | GPIO_Pin_2;
	GPIO_Sturuct.GPIO_Speed = GPIO_Speed_50MHz;
	
	GPIO_Init(GPIOA, &GPIO_Sturuct);
	GPIO_SetBits(GPIOA, GPIO_Pin_1 | GPIO_Pin_2);

}

2、LED灯电平翻转程序

通过GPIO_ReadOutputDataBit()函数读取LED的电平状态,当检测为低电平时通过GPIO_SetBits()函数置为高电平,反之检测为低电平时通过GPIO_ResetBits()置为低电平。

void LED_Turn_1(void)
{
	if(GPIO_ReadOutputDataBit(GPIOA, GPIO_Pin_1) == 0)
	{
		GPIO_SetBits(GPIOA, GPIO_Pin_1);
	}
	else
		
		GPIO_ResetBits(GPIOA, GPIO_Pin_1);
		
}	

 四、主函数

uint8_t KeyNum;定义一个全局变量,将Key_GetNum()函数返回的值赋给KeyNum,当KeyNum的值为1时证明按键按下,将LED的电平进行翻转。

int main (void)
{
	LED_Init();
	Key_Init();
	
	while(1)
	{
		KeyNum = Key_GetNum();
//		LED_On_1();
		if( KeyNum == 1)
		{
				LED_Turn_1();
				Delay_ms(500);
	}
		
			if( KeyNum == 2)
		{

				LED_Turn_2();
				Delay_ms(500);
	}
	
	}		
	
	
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值