一、控制电路
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);
}
}
}