工程可见Github<传送门>


一、主要代码

main.c

/*******************************************************************************
* 文件名:main.c
* 描  述:
* 作  者:CLAY
* 版本号:v1.0.0
* 日  期: 2019年1月24日
* 备  注:按键B1控制LED1的亮灭
*         
*******************************************************************************
*/

#include "stm32f10x.h"
#include "led.h"
#include "key.h"
#include "timer.h"


int main(void)
{
	LEDInit();
	KeyInit();
	TIM2Init(2000, 72);//定时2ms
	
	while(1)
	{	
		KeyDriver();
	}
}

void KeyAction(int code)
{
	if(code == 1)
	{
		GPIOC->ODR ^= (1<<8);//PC8不断取反
		GPIOD->ODR |= (1<<2);//PD2置1,使能573锁存器
		GPIOD->ODR &= ~(1<<2);//PD2清0,关闭573锁存器
	}
}



key.c

#include "key.h"

u8 KeySta[4] = {1, 1, 1, 1};

extern void KeyAction(int code);

void KeyInit(void)
{
	GPIO_InitTypeDef GPIO_InitStructure;
	
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_GPIOB, ENABLE);//设能PC和PD口
	
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0|GPIO_Pin_8;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;//浮空输入,也不需要设置相应的Speed
	GPIO_Init(GPIOA, &GPIO_InitStructure);
	
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1|GPIO_Pin_2;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;//浮空输入,也不需要设置相应的Speed
	GPIO_Init(GPIOB, &GPIO_InitStructure);
}

void KeyDriver(void)
{
	int i;
	static u8 backup[4] = {1, 1, 1, 1};
	
	for(i=0; i<4; i++)
	{
		if(backup[i] != KeySta[i])
		{
			if(backup[i] != 0)
			{
				KeyAction(i+1);
			}	
			backup[i] = KeySta[i];
		}			
	}
}

void KeyScan(void)
{
	int i; 
	static u8 keybuf[4] = {0xFF, 0xFF, 0xFF, 0xFF};
	
	keybuf[0] = (keybuf[0]<<1) | KEY1;
	keybuf[1] = (keybuf[1]<<1) | KEY2;
	keybuf[2] = (keybuf[2]<<1) | KEY3;
	keybuf[3] = (keybuf[3]<<1) | KEY4;
	
	for(i=0; i<4; i++)
	{
		if(keybuf[i] == 0x00)
		{
			KeySta[i] = 0;
		}
		else if (keybuf[i] == 0xFF)
		{
			KeySta[i] = 1;
		}
	}
}



key.h

#ifndef _KEY_H
#define _KEY_H

#include "stm32f10x.h"

#define KEY1 GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0)
#define KEY2 GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_8)
#define KEY3 GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_1)
#define KEY4 GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_2)

void KeyInit(void);
void KeyScan(void);
void KeyDriver(void);

#endif

二、程序讲解

CT117E对应按键部分原理图
蓝桥嵌入式之 按键控制LED闪烁
1、按键输入模式为浮空输入

2、为了方便读入按键状态,在key.h中进行了用GPIO_ReadInputDataBit进行了宏定义!

三、注意事项

按键的扫描时间是2ms,所以定时TIM2Init(2000, 72); // 2ms

相关文章:

  • 2021-10-26
  • 2021-12-29
  • 2021-12-08
  • 2021-11-01
  • 2021-11-16
  • 2021-06-04
  • 2021-12-10
  • 2021-08-01
猜你喜欢
  • 2021-09-20
  • 2021-08-11
  • 2022-12-23
  • 2021-09-15
  • 2021-11-17
  • 2022-12-23
  • 2021-11-18
相关资源
相似解决方案