新闻中心

stm32学习之五

作者: 时间:2016-12-03 来源:网络 收藏
按键输入的学习(key_polling):

目标:通过按键的输入,实现LED灯的反转等操作。

要实现按键的输入的读取,必须要实现一个key.c和key.h的文件的编写,这里,利用库函数的编写原则(仿照
库函数的编写方法),获取按键的动作。
首先,编写key.h函数:
#ifndef _KEY_H
#define _KEY_H
#include "stm32f10x.h"
#define KEY_ON 0
#define KEY_OFF 1
void key_Init(void);
uint8_t key_Scan( GPIO_TypeDef * GPIOx, uint16_t GPIO_Pin );
void delay(uint32_t count);

本文引用地址://m.amcfsurvey.com/article/201612/325175.htm

#endif

这里:
定义了KEY_ON和KEY_OFF的宏定义,主要是由于按键按下的时候,会导致读取的数据为0,因此,就按上面的
定义规范了。

然后,编写:
key.c文件:
#include "stm32f10x.h"
#include "key.h"
void key_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOE,ENABLE);

GPIO_InitStructure.GPIO_Pin=GPIO_Pin_5;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IPU;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;

GPIO_Init(GPIOE,&GPIO_InitStructure);

GPIO_SetBits(GPIOC,GPIO_Pin_5);
}

uint8_t key_Scan( GPIO_TypeDef * GPIOx, uint16_t GPIO_Pin )
{
if(GPIO_ReadInputDataBit(GPIOx,GPIO_Pin_5)==KEY_ON)
{
delay(5000);
if(GPIO_ReadInputDataBit(GPIOx,GPIO_Pin_5)==KEY_ON)
{
while(GPIO_ReadInputDataBit(GPIOx,GPIO_Pin_5)==KEY_ON);
return KEY_ON;
}
else
{
return KEY_OFF;
}
}
else
{
return KEY_OFF;
}

}

void delay(uint32_t count)
{
for(;count>0;count--);
}

这里,初始化了按键的操作,以及延时,防抖动的操作。
同时:
uint8_t key_Scan( GPIO_TypeDef * GPIOx, uint16_t GPIO_Pin )
是仿照库函数的写法:
uint8_t GPIO_ReadInputDataBit ( GPIO_TypeDef * GPIOx, uint16_t GPIO_Pin )
然后,就是led.c和led.h的编写了
led.c代码如下:
#include "led.h"
void LED_GPIO_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC,ENABLE);

GPIO_InitStructure.GPIO_Pin=GPIO_Pin_3|GPIO_Pin_4|GPIO_Pin_5;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_OD;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;

GPIO_Init(GPIOC,&GPIO_InitStructure);

GPIO_SetBits(GPIOC,GPIO_Pin_3|GPIO_Pin_4|GPIO_Pin_5);
}
led.h代码如下:
#ifndef _LED_H
#define _LED_H
#include "stm32f10x.h"

#define ON 1
#define OFF 0

#define LED1(a) if (a)
GPIO_ResetBits(GPIOC,GPIO_Pin_3);
else
GPIO_SetBits(GPIOC,GPIO_Pin_3)
#define LED2(a) if (a)
GPIO_ResetBits(GPIOC,GPIO_Pin_4);
else
GPIO_SetBits(GPIOC,GPIO_Pin_4)
#define LED3(a) if (a)
GPIO_ResetBits(GPIOC,GPIO_Pin_5);
else
GPIO_SetBits(GPIOC,GPIO_Pin_5)
void LED_GPIO_Config(void);


#endif
其实,是复制原来的代码而已,也可以省略很多的东西的。
接着就是主函数的编写了:
/******************** (C) COPYRIGHT 2013 **************************
* 文件名 :main.c
* 描述 :用3.5.0版本建的工程模板。
* 实验平台:野火STM32开发板
* 库版本 :ST3.5.0
*
* 作者 :wit_yuan
* 版本 : v1.0
* 时间 : 2013年4月27日
**********************************************************************************/
#include "stm32f10x.h"
#include "led.h"
#include "SysTick.h"
#include "key.h"
/*
* 函数名:main
* 描述 : 主函数
* 输入 :无
* 输出 : 无
*/
int main(void)
{
LED_GPIO_Config();
//SysTick_Init();
key_Init();

while(1)
{
if(key_Scan( GPIOE, GPIO_Pin_5 )==KEY_ON)
{
GPIO_WriteBit(GPIOC,GPIO_Pin_3,(BitAction)
(1-GPIO_ReadOutputDataBit (GPIOC,GPIO_Pin_3)));
}
}

}

由此,基本上完毕程序的编写。



关键词:stm32按键输

评论


技术专区

关闭