STMSTM32按键输入控制LED、蜂鸣器
基于stm32f407,为实现以上功能,可将问题分为三个部分:LED、蜂鸣器和按键输入。
led部分
LED部分
c文件中分为三部分:①使能IO口时钟,②初始化IO口模式,③使IO口输出高电平
#include "stm32f4xx.h"
#include "led.h"
void LED_Init()
{
GPIO_InitTypeDef GPIO_InitLed;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF,ENABLE);
GPIO_InitLed.GPIO_Pin=GPIO_Pin_9|GPIO_Pin_10;
GPIO_InitLed.GPIO_Mode=GPIO_Mode_OUT;
GPIO_InitLed.GPIO_OType=GPIO_OType_PP;
GPIO_InitLed.GPIO_PuPd=GPIO_PuPd_UP;
GPIO_InitLed.GPIO_Speed=GPIO_High_Speed;
GPIO_Init(GPIOF,&GPIO_InitLed);
GPIO_SetBits(GPIOF,GPIO_Pin_9|GPIO_Pin_10);
}
h文件中对LED_Init 进行申明,同时对两个LED灯通过位带操作进行定义:
#include "stm32f4xx.h"
#ifndef __LED_H
#define __LED_H
#define LED0 PFout(9)
#define LED1 PFout(10)
void LED_Init(void);
#endif
蜂鸣器部分
c文件中分为三部分:①使能IO口时钟,②初始化IO口模式,③使IO口输出低电平
#include "beep.h"
#include "stm32f4xx.h"
void BEEP_Init(void)
{
GPIO_InitTypeDef GPIO_InitBeep;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF,ENABLE);
GPIO_InitBeep.GPIO_Pin=GPIO_Pin_8;
GPIO_InitBeep.GPIO_Mode=GPIO_Mode_OUT;
GPIO_InitBeep.GPIO_OType=GPIO_OType_PP;
GPIO_InitBeep.GPIO_PuPd=GPIO_PuPd_DOWN;
GPIO_InitBeep.GPIO_Speed=GPIO_High_Speed;
GPIO_Init(GPIOF,&GPIO_InitBeep);
GPIO_ResetBits(GPIOF,GPIO_Pin_8);
}
h文件部分,申明函数BEEP_Init,定义BEEP
#include "stm32f4xx.h"
#ifndef __BEEP_H
#define __BEEP_H
void BEEP_Init(void);
#define BEEP PFout(8)
#endif
按键输入部分
C文件中含有两个函数,第一个函数KEY_Init:①使能IO口时钟,②初始化IO口模式
第二个函数为按键扫描函数,KEY0检测到被按下后返回1给KEY-Scan if(mode)key_up=1;
可实现连续扫描(mode=1)和不连续扫描(mode=0)。
#include "key.h"
#include "stm32f4xx.h"
#include "delay.h"
void KEY_Init(void)
{
GPIO_InitTypeDef GPIO_InitKey;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOE,ENABLE);
GPIO_InitKey.GPIO_Pin=GPIO_Pin_4|GPIO_Pin_3|GPIO_Pin_2;
GPIO_InitKey.GPIO_PuPd=GPIO_PuPd_UP;
GPIO_InitKey.GPIO_Mode=GPIO_Mode_IN;
GPIO_InitKey.GPIO_Speed=GPIO_High_Speed;
GPIO_Init(GPIOE,&GPIO_InitKey);
}
u8 KEY_Scan(u8 mode)
{
static u8 key_up=1;
if(mode)key_up=1;
if(key_up&&(KEY0==0))
{
delay_ms(10);
key_up=0;
if(KEY0==0)return 1;
}else if(KEY0==1)
key_up=1;
return 0;
}
h文件中,对c文件中的两个函数进行申明,并对按键进行定义。
#ifndef __KEY_H
#define __KEY_H
#include "stm32f4xx.h"
void KEY_Init(void);
u8 KEY_Scan(u8);
#define KEY0 GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_4)
#endif
main函数
#include "stm32f4xx.h"
#include "delay.h"
#include "led.h"
#include "beep.h"
#include "key.h"
int main(void)
{
u8 key;
KEY_Init();
delay_init(168);
LED_Init();
BEEP_Init();
while(1)
{
key=KEY_Scan(0);
if(key!=0)
{
LED0=!LED0;
LED1=!LED1;
BEEP=!BEEP;
}
else delay_ms(10);
}
}