3-4按键控制LED & 光敏传感器控制蜂鸣器

1234
uint8_t GPIO_ReadInputDataBit(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin);//用来读取输入数据寄存器某一个位的输入值uint16_t GPIO_ReadInputData(GPIO_TypeDef* GPIOx);//读取整个输入数据寄存器uint8_t GPIO_ReadOutputDataBit(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin);//用来读取输出数据寄存器某一个位的输入值uint16_t GPIO_ReadOutputData(GPIO_TypeDef* GPIOx);//读取整个输出数据寄存器

main.c

123456789101112131415161718192021222324
#include "stm32f10x.h"                  // Device header#include "delay.h"#include "LED.h"#include "key.h" uint8_t KeyNum;//这里定义的是全局变量,和key.c中定义的局部变量是不一样的int main(void){	LED_Init();	KEY_Init();	while(1)	{		KeyNum = Key_GetNum();		if(KeyNum == 1)		{			LED1_Turn();		}		else if(KeyNum == 2)		{			LED2_Turn();		}	}} 

LED.c

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
#include "stm32f10x.h"                  // Device header void LED_Init(void){	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);	GPIO_InitTypeDef GPIO_InitStructure;	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1 | GPIO_Pin_2;	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;	GPIO_Init(GPIOA, &GPIO_InitStructure);	GPIO_SetBits(GPIOA,GPIO_Pin_1 | GPIO_Pin_2);} void LED1_ON(void){	GPIO_ResetBits(GPIOA,GPIO_Pin_1);}void LED1_OFF(void){	GPIO_SetBits(GPIOA,GPIO_Pin_1);}void LED1_Turn(void){	if(GPIO_ReadOutputDataBit(GPIOA,GPIO_Pin_1) == 0)//读取PA1的值,类似LD=,做判断用	{		GPIO_SetBits(GPIOA,GPIO_Pin_1);	}	else	{		GPIO_ResetBits(GPIOA,GPIO_Pin_1);	}}void LED2_ON(void){	GPIO_ResetBits(GPIOA,GPIO_Pin_2);}void LED2_OFF(void){	GPIO_SetBits(GPIOA,GPIO_Pin_2);}void LED2_Turn(void){	if(GPIO_ReadOutputDataBit(GPIOA,GPIO_Pin_2) == 0)	{		GPIO_SetBits(GPIOA,GPIO_Pin_2);	}	else	{		GPIO_ResetBits(GPIOA,GPIO_Pin_2);	}} 

key.c

123456789101112131415161718192021222324252627282930313233343536
#include "stm32f10x.h"                  // Device header#include "Delay.h"void KEY_Init(void){	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);	GPIO_InitTypeDef GPIO_InitStructure;	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;//ÒòΪҪ¶ÁÈ¡°´¼ü£¬Ñ¡ÔñÉÏÀ­ÊäÈë	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1 | GPIO_Pin_11;	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;	GPIO_Init(GPIOB, &GPIO_InitStructure);} uint8_t Key_GetNum(void){	uint8_t KeyNum = 0;	if ( GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_1) == 0 )	{		Delay_ms(20);//延时20ms因为会抖动		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;} 
🔍 ×