通过几个按键,来控制LED灯的开关状态。没有涉及到中断,只是简单的按键程序
程序包括key.c,key.h;led.c,led.h;以及main函数
一、LED程序
led.h
#ifndef __LED__H
#define __LED__H
#include "stm32f10x.h"
#include "sys.h"
#define LED1 PBout(8)// PB8
#define LED2 PBout(9)// PB9
void LED_Init(void);
#endif
led.c
#include "stm32f10x.h"
#include "led.h"
void LED_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8 | GPIO_Pin_9;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_SetBits(GPIOB,GPIO_Pin_8);
GPIO_SetBits(GPIOB,GPIO_Pin_9);
}
二、KEY程序
按键采用上拉输入,外接上拉电阻
key.h
#ifndef __KEY__H
#define __KEY__H
#include "sys.h"
#include "stm32f10x.h"
#define S1 GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_1)//读取按键1
#define S2 GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_2)//读取按键2
#define S3 GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_3)//读取按键3
#define S4 GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_4)//读取按键4
#define KEY_ON 0
#define KEY_OFF 1
void KEY_Init(void);
u8 KEY_Scan(GPIO_TypeDef* GPIOx, u16 GPIO_Pin);
#endif
key.c
#include "key.h"
#include "delay.h"
void KEY_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
//打开PA口时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3 | GPIO_Pin_4;
//端口速度
//GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
//端口模式,此为输入上拉模式
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
u8 KEY_Scan(GPIO_TypeDef* GPIOx, u16 GPIO_Pin)
{
/*检查是否有按键按下*/
if(GPIO_ReadInputDataBit(GPIOx,GPIO_Pin) == KEY_ON)
{
/*延时消抖*/
delay_ms(50);
if(GPIO_ReadInputDataBit(GPIOx,GPIO_Pin) == KEY_ON)
{
/*等待按键释放*/
while(GPIO_ReadInputDataBit(GPIOx,GPIO_Pin) == KEY_ON);
return KEY_ON;
}
else
return KEY_OFF;
}
else
return KEY_OFF;
}
主函数
#include "key.h"
#include "led.h"
#include "delay.h"
#include "sys.h"
//LED灯闪5下
int main(void)
{
u8 i;
LED_Init();//LED初始化
KEY_Init();//按键初始化
delay_init();//延时初始化
while(1)
{
LED1=1;
LED2=1;
if(KEY_Scan(GPIOA,GPIO_Pin_3) == KEY_ON)
{
for(i=0;i<5;i++)
{
LED1=1;delay_ms(200);
LED1=0;delay_ms(200);
}
}
if(KEY_Scan(GPIOA,GPIO_Pin_4) == KEY_ON)
{
for(i=0;i<5;i++)
{
LED2=1;delay_ms(100);
LED2=0;delay_ms(100);
LED1=1;delay_ms(100);
LED1=0;delay_ms(100);
}
}
}
}
程序很简单,通过扫描GPIO端口电平的状态,来判断按键是否按下