一、硬件电路分析
按键的具体硬件电路原理图如下:
大致就这两种:
KEY1 带上拉电路的,按键按下,PB12接地,输入低电平。
KEY2 不带上拉电路的,按键按下,PB13接地,输入低电平。
二、KEY按键配置
1. GPIO时钟配置
GPIO时钟配置函数
- void RCC_APB2PeriphClockCmd(uint32_t RCC_APB2Periph, FunctionalState NewState);
复制代码
本次配置如下
- RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOB, ENABLE); // 使能PB端口时钟
复制代码
2. GPIO初始化配置
工作模式可以参考:STM32F103:GPIO八种工作原理详解
本次GPIO初始化配置工作模式为:GPIO_Mode_IPU 上拉输入,因为按键按下输入的电平是低电平,上拉输入会使低电平输入更加容易读取。
GPIO初始化函数
- void GPIO_Init(GPIO_TypeDef* GPIOx, GPIO_InitTypeDef* GPIO_InitStruct);
复制代码
本次配置如下:
- GPIO_InitTypeDef GPIO_InitStructure;
- GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12|GPIO_Pin_13; // PB14,PB15
- GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; //上拉输入
- GPIO_Init(GPIOB, &GPIO_InitStructure); //初始化PB端口
复制代码
3. GPIO输入读取配置
GPIO输入读取函数
返回值:低电平----0,高电平----1。
- uint8_t GPIO_ReadInputDataBit(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin)
复制代码
本次配置如下:
- #define KEY1 GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_12)//读取按键1
- #define KEY2 GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_13)//读取按键2
复制代码
三、KEY按键实验
1. KEY按键实验功能介绍
本次实验主要实现的功能就是:
按KEY1,key加1,然后通过串口printf()函数,打印输出key值。
按KEY2,key减1,然后通过串口printf()函数,打印输出key值。
2. 配置程序
key.c
- #include "KEY.h"
- /*************** 配置KEY用到的I/O口 *******************/
- void KEY_GPIO_Config(void)
- {
- RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); // 使能PB端口时钟
-
- GPIO_InitTypeDef GPIO_InitStructure;
- GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12|GPIO_Pin_13; // PB12,PB13
- GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; //上拉输入模式
- GPIO_Init(GPIOB, &GPIO_InitStructure); //初始化PB端口
- }
复制代码
key.h
- #ifndef __KEY_H
- #define __KEY_H
- #include "stm32f10x.h"
- #define KEY1 GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_12)//读取按键1
- #define KEY2 GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_13)//读取按键2
- void KEY_GPIO_Config(void); //Key初始化
- #endif
复制代码
3. 具体实现程序
main.c
- #include "stm32f10x.h"
- #include <stdio.h>
- #include "delay.h"
- #include "KEY.h"
- #include "Uart1.h"
- int main (void)
- {
- KEY_GPIO_Config(); //KEY初始化
- Uart1_init(); //串口1初始化
-
- static u8 key_up=1; //按键松开标志
- int key=0; //按键计数
- while(1)
- {
- if((key_up==1)&&(KEY1==0||KEY2==0))
- {
- delay_ms(10); //消抖
- key_up=0;
- if(KEY1==0)
- {
- key++;
- printf("Key=%d",key);
- }
- else if(KEY2==0)
- {
- key--;
- printf("Key=%d",key);
- }
- }
- else if(KEY1==1&&KEY2==1) //按键松开
- {
- key_up=1;
- }
- }
- }
复制代码
————————————————
版权声明:根号五
|