STM32例子--------按键控制LED灯
此工程需要编写以下五个文档
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
#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_13
void Key_GPIO_Config(void);
uint8_t Key_Scan(GPIO_TypeDef *GPIOx,uint16_t GPIO_Pin);
#endif /* __KEY_H */
- KEY.c
#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
#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;
}
- 仿真图