STM32————按键实现控制LED灯

按键控制LED灯分两种情况
1:按下一亮,直到第二次按下熄灭
2:按一下常亮,松开就熄灭
/LED.h文件/
#ifndef _ LED.h
#define _ LED.h
#include “stm32f10x.h”
//宏定义LED灯
#define LEDPORT GPIOB //IO组
#define LED1 GPIO_Pin_0 //定义LED1
#define LED2 GPIO_Pin_1 //定义LED2
//宏定义按键
#define KEYPORT GPIOA
#define KEY1 GPIO_Pin_0
/LED.h文件/
/LED.c文件/
#include “LED.h”
//LED灯初始化
Void Init_Led(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);//使能其所在时钟
GPIO_InitStructure.GPIO_Pin= LED1|| LED2 //设置引脚
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP; //设置模式
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;//设置速度
GPIO_Init(LEDPORT,&GPIO_InitStructure);
}
//按键初始化
Void Init_ Key(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);//使能其所在时钟
GPIO_InitStructure.GPIO_Pin= KEY1; //设置引脚
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP; //设置模式
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;//设置速度
GPIO_Init(KEYPORT,&GPIO_InitStructure);
}
/LED.c文件/

//第一种情况1:按下一亮,直到第二次按下熄灭
Main()
{
Int num = 0;
While(1)
{
//假设按下states = 0
int states = GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_0);
if(states==0&&((num%2)==0))
{
//按键刚松开那一刻,states马上变为0 if(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_5)==0)//再判断是否为低电平
{
//给GPIOB端口5赋值为高电平,实现LED亮

GPIO_ResetBits(GPIOB,GPIO_Pin_5);
Num ++;
}
}
else
{
if(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_5)==0)
{

             //给GPIOB端口5赋值为低电平,实现LED灭
                  GPIO_SetBits(GPIOB,GPIO_Pin_5);

Num ++;
}
}
}
}
2:按一下常亮,松开就熄灭
//过程省略
int states = GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_0);
//如果按下了,就亮
if (states == 0)
{
GPIO_ResetBits(GPIOB,GPIO_Pin_5);
}
//如果松开了,就熄灭
Else
{
GPIO_SetBits(GPIOB,GPIO_Pin_5);
}

猜你喜欢

转载自blog.csdn.net/News53231323/article/details/113245199