按键点亮led灯

原理图:


K0这个按键按下时,开发板D1这个灯亮,松开,灯灭


 代码如下:

#include "stm32f4xx.h"  


void LED_Init(void)
{
	//1.定义一个GPIO外设的结构体变量  
	GPIO_InitTypeDef GPIO_InitStructure;
	
	//RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOE|RCC_AHB1Periph_GPIOF, ENABLE);
  RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF, ENABLE);
	//3.对结构体变量的成员进行赋值
	GPIO_InitStructure.GPIO_Mode 	= GPIO_Mode_OUT;				//输出模式
	GPIO_InitStructure.GPIO_OType 	= GPIO_OType_PP;				//推挽输出
	GPIO_InitStructure.GPIO_Speed 	= GPIO_Speed_100MHz;			//输出速率100MHZ
	GPIO_InitStructure.GPIO_PuPd 	= GPIO_PuPd_UP;					//上拉输出
	
	//4.初始化GPIO
	//GPIO_InitStructure.GPIO_Pin 	= GPIO_Pin_9|GPIO_Pin_10;		//引脚
	GPIO_InitStructure.GPIO_Pin 	= GPIO_Pin_9;		//引脚
	GPIO_Init(GPIOF, &GPIO_InitStructure);
		
	//GPIO_InitStructure.GPIO_Pin 	= GPIO_Pin_13|GPIO_Pin_14;		//引脚
	//GPIO_Init(GPIOE, &GPIO_InitStructure);

	GPIO_SetBits(GPIOF,GPIO_Pin_9);		//设置高电平  LED灭
	//	GPIO_SetBits(GPIOF,GPIO_Pin_9|GPIO_Pin_10);		//设置高电平  LED灭
	//GPIO_SetBits(GPIOE,GPIO_Pin_13|GPIO_Pin_14);	//设置高电平  LED灭	
}


void KEY_Init(void)
{
	//1.定义一个GPIO外设的结构体变量  
	GPIO_InitTypeDef GPIO_InitStructure;
	
	//2.打开外设时钟  GPIOA  PA0
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);

	//3.对结构体变量的成员进行赋值
	GPIO_InitStructure.GPIO_Mode 	= GPIO_Mode_IN;					//输入模式
	GPIO_InitStructure.GPIO_PuPd 	= GPIO_PuPd_UP;					//上拉输出
	
	//4.初始化GPIO
	GPIO_InitStructure.GPIO_Pin 	= GPIO_Pin_9;					//引脚
	GPIO_Init(GPIOB, &GPIO_InitStructure);
	
}


int main()
{
	KEY_Init();  //按键的初始化
	LED_Init();	 //LED的初始化
	
	while(1)
	{
		if( GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_9) == RESET )	//说明被按下
		{
			GPIO_ResetBits(GPIOF,GPIO_Pin_9);	//设置低电平  LED亮
		}
		else
		{
			GPIO_SetBits(GPIOF,GPIO_Pin_9);		//设置高电平  LED灭	
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq_15267341/article/details/132950336