首页
学习
活动
专区
圈层
工具
发布
清单首页STM32文章详情

按键控制LED灯

STM32--------按键控制LED灯

知识介绍

工程文件放置

只有在添加进这一串之后,才能使用头文件集合 stm32f10x_conf.h

选择类型

初始化时钟从哪找

在stm32f10x_rcc.c中。

断言函数

此工程需要编写以下五个文档

LED.h

代码语言:javascript
复制
#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.c

代码语言:javascript
复制
#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

代码语言:javascript
复制
#ifndef __KEY_H#d#include "stm32f10x.h"#define  KEY_ON      1#define  KEY_OFF     0#define KEY1_GPIO_CLK   RCC_APB2Periph_GPIOA#define KEY1_GPIO_PORT   GPIOA#define KEY1_GPIO_PIN   GPIO_Pin_0#define KEY2_GPIO_CLK   RCC_APB2Periph_GPIOC#define KEY2_GPIO_PORT   GPIOC#define KEY2_GPIO_PIN   GPIO_Pin_13void Key_GPIO_Config(void);uint8_t Key_Scan(GPIO_TypeDef *GPIOx,uint16_t GPIO_Pin);#endif /* __KEY_H */

KEY.c

代码语言:javascript
复制
#include "KEY.h"void Key_GPIO_Config(void){ GPIO_InitTypeDef GPIO_InitStructure; RCC_APB2PeriphClockCmd(KEY1_GPIO_CLK|KEY2_GPIO_CLK,ENABLE);  //定义第一个按键 GPIO_InitStructure.GPIO_Pin = KEY1_GPIO_PIN; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; GPIO_Init(KEY1_GPIO_PORT, &GPIO_InitStructure); //定义第二个按键 GPIO_InitStructure.GPIO_Pin = KEY2_GPIO_PIN;  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; GPIO_Init(KEY2_GPIO_PORT, &GPIO_InitStructure);
 } uint8_t Key_Scan(GPIO_TypeDef *GPIOx,uint16_t GPIO_Pin){ if( GPIO_ReadInputDataBit(GPIOx, GPIO_Pin) == KEY_ON ) {  while( GPIO_ReadInputDataBit(GPIOx, GPIO_Pin) == KEY_ON );  return KEY_ON; } else return KEY_OFF;}

main.c

代码语言:javascript
复制
#include "stm32f10x.h"   // 相当于51单片机中的  #include <reg51.h>#include "LED.h"#include "KEY.h" int main(void){LED_GPIO_Config(); Key_GPIO_Config();   while (1)  {    if ( Key_Scan(KEY1_GPIO_PORT,KEY1_GPIO_PIN) == KEY_ON )              LED_B_TOGGLE;    if ( Key_Scan(KEY2_GPIO_PORT,KEY2_GPIO_PIN) == KEY_ON )         LED_R_TOGGLE;    }

仿真图

举报
领券