STM32--------按键控制LED灯
知识介绍
工程文件放置
只有在添加进这一串之后,才能使用头文件集合 stm32f10x_conf.h
在stm32f10x_rcc.c中。
此工程需要编写以下五个文档
1.LED.h
#ifndef __LED_H
#define __LED_H
#include "stm32f10x.h"
#define LED_B_GPIO_PIN GPIO_Pin_1
#define LED_R_GPIO_PIN GPIO_Pin_5
#define LED_GPIO_PORT GPIOB
#define LED_GPIO_CLK RCC_APB2Periph_GPIOB
//反转
#define LED_R_TOGGLE {LED_GPIO_PORT->ODR ^= LED_R_GPIO_PIN;}//异或可以改变原来的状态
#define LED_B_TOGGLE {LED_GPIO_PORT->ODR ^= LED_B_GPIO_PIN;}//异或可以改变原来的状态
void LED_GPIO_Config(void);
#endif /* __LED_H */
- LED.h
#include "YANG_LED.h"
void LED_GPIO_Config(void)
{
/*定义3个GPIO_InitTypeDef 类型的结构体*/
GPIO_InitTypeDef GPIO_InitStruct1;
GPIO_InitTypeDef GPIO_InitStruct2;
/*开启 LED 相关的 GPIO 外设时钟*/
RCC_APB2PeriphClockCmd(LED_GPIO_CLK, ENABLE);
GPIO_InitStruct1.GPIO_Pin = LED_B_GPIO_PIN;
GPIO_InitStruct2.GPIO_Pin = LED_R_GPIO_PIN;
GPIO_InitStruct1.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStruct1.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStruct2.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStruct2.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(LED_GPIO_PORT, &GPIO_InitStruct1);
GPIO_Init(LED_GPIO_PORT, &GPIO_InitStruct2);
}
- KEY.h
#ifndef __KEY_H
#define __KEY_H
#include "stm32f10x.h"
int anjian(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin);
void KeyInit(void);
#endif /* __KEY_H */
- KEY.c
#include "key.h"
void KeyInit(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC | RCC_APB2Periph_GPIOC, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9 | GPIO_Pin_8;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;//设置端口模式为浮空输入
GPIO_Init(GPIOC, &GPIO_InitStructure);
}
int anjian(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin)
{
u8 anjianbianliang;
int anjianzhi;
anjianbianliang=GPIO_ReadInputDataBit(GPIOx, GPIO_Pin);
if(anjianbianliang==1)
anjianzhi=1;
else if(anjianbianliang==0)
anjianzhi=0;
return anjianzhi;
}
- main.c
#include "stm32f10x.h" // 相当于51单片机中的 #include
#include "LED.h"
#include "KEY.h"
int main(void)
{
LED_GPIO_Config();
Key_Init();
while (1)
{
if(anjian(GPIOC,GPIO_Pin_8)==0)
{
LED_G(ON);
}
if(anjian(GPIOC,GPIO_Pin_9)==0)
{
LED_G(OFF);
}
}
- 仿真图
如果想了解更多物联网、智能家居项目知识,可以关注我的项目实战专栏和软硬结合专栏。 欢迎关注公众号了解更多。
编写不易,感谢支持。