


电路板按钮diagram.png

看看电路原理图,我们发现有三个按钮S1,S2和S3. 它们都连接到左端的GPIO端口stm32 矩阵键盘扫描原理stm32 矩阵键盘扫描原理,并在右端接地. 可以根据电路特性编写按钮的控制代码.

与之前的LED控制代码相比,这次代码向led.h添加了一个宏定义LED_REV来控制LED灯的翻转(如果在开始时关闭LED灯,则在执行后将点亮) LED_REV;如果LED指示灯为亮,则在执行LED_REV后开始点亮并熄灭.

#ifndef __LED_H
#define __LED_H
#include "stm32f10x.h"
#define ON 0
#define OFF 1
#define LED2(a) if(a) GPIO_SetBits( GPIOE, GPIO_Pin_5 ); else GPIO_ResetBits( GPIOE, GPIO_Pin_5 )
#define LED3(a) if(a) GPIO_SetBits( GPIOB, GPIO_Pin_5 ); else GPIO_ResetBits( GPIOB, GPIO_Pin_5 )
//新添加的代码
#define LED2_REV GPIO_WriteBit(GPIOE, GPIO_Pin_5, (BitAction)(1-(GPIO_ReadOutputDataBit(GPIOE, GPIO_Pin_5))))
#define LED3_REV GPIO_WriteBit(GPIOB, GPIO_Pin_5, (BitAction)(1-(GPIO_ReadOutputDataBit(GPIOB, GPIO_Pin_5))))
void LED_Init(void);
#endif
#ifndef __KEY_H
#define __KEY_H
#include "stm32f10x.h"
//用宏定义表示开关的开闭状态
#define KEY_ON 0
#define KEY_OFF 1
//按键初始化函数
void KEY_Init(void);
//不精确延时函数
void Delay( __IO u32 nCount );
//三个按键的扫描函数
uint8_t Key1_Scan( void );
uint8_t Key2_Scan( void );
uint8_t Key3_Scan( void );
#endif
#include "stm32f10x.h"
#include "key.h"
//通过循环产生一个延时
void Delay( __IO u32 nCount )
{
for( ; nCount > 0; --nCount );
}
/**********************************************
按键初始化函数,与普通GPIO口初始化类似。
但是输入输出方式使用上拉输入,速率也不一样。
**********************************************/
void KEY_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOE, ENABLE );
GPIO_InitStructure.GPIO_Pin = 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( GPIOE, &GPIO_InitStructure );
}
/*******************************************************
按键S1的扫描函数。
在检测到S1处于按下状态时,先通过延时去除抖动。
当再次检测到S1按键处于按下状态时,则认为用户按下了S1。
如果while循环检测到用户释放按键,那么返回KEY_ON。
*******************************************************/
uint8_t Key1_Scan( void )
{
if( GPIO_ReadInputDataBit( GPIOE, GPIO_Pin_4 ) == KEY_ON )
{
Delay(10000);
if( GPIO_ReadInputDataBit( GPIOE, GPIO_Pin_4 ) == KEY_ON )
{
while( GPIO_ReadInputDataBit( GPIOE, GPIO_Pin_4 ) == KEY_ON );
return KEY_ON;
}
else return KEY_OFF;
}
else return KEY_OFF;
}
uint8_t Key2_Scan( void )
{
if( GPIO_ReadInputDataBit( GPIOE, GPIO_Pin_3 ) == KEY_ON )
{
Delay(10000);
if( GPIO_ReadInputDataBit( GPIOE, GPIO_Pin_3 ) == KEY_ON )
{
while( GPIO_ReadInputDataBit( GPIOE, GPIO_Pin_3 ) == KEY_ON );
return KEY_ON;
}
else return KEY_OFF;
}
else return KEY_OFF;
}
uint8_t Key3_Scan( void )
{
if( GPIO_ReadInputDataBit( GPIOE, GPIO_Pin_2 ) == KEY_ON )
{
Delay(10000);
if( GPIO_ReadInputDataBit( GPIOE, GPIO_Pin_2 ) == KEY_ON )
{
while( GPIO_ReadInputDataBit( GPIOE, GPIO_Pin_2 ) == KEY_ON );
return KEY_ON;
}
else return KEY_OFF;
}
else return KEY_OFF;
}
本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-288592-1.html
您好