STM32按键代码【库函数版本】

目录

  • KEY.h文件
  • KEY.c文件
  • main.c文件

作为常见的输入设备,通过按下达到某些指定的预期的功能。

我们通过调用函数GPIO_ReadInputDataBit()来读取IO口的状态。

废话不多说,直接上代码

KEY.h文件

#ifndef __KEY_H
#define __KEY_H

void Key_Init(void);
uint16_t Key_GetNum(void);

#endif

KEY.c文件

#include "stm32f10x.h"                  // Device header
#include "Delay.h"


void Key_Init(void)
{
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
	
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; // 上拉输入,因为我的按键一端直接接的是GND,所以采取上拉输入
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStructure);
	
}

uint16_t Key_GetNum(void)
{
	uint16_t KeyNum = 0;
	if(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_9) == 0)
	{
		Delay_ms(20);
		while(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_9) == 0);
		Delay_ms(20);
		KeyNum = 1;
	}
	return KeyNum;
}

main.c文件

#include "stm32f10x.h"                  // Device header
#include "LED.h"
#include "Delay.h"
#include "KEY.h"

uint16_t Num = 0;
int main()
{
	LED_Init();
	Key_Init();
	while(1)
	{
		Num = Key_GetNum();
		if(Num == 1)
		{
			if(GPIO_ReadOutputDataBit(GPIOA, GPIO_Pin_0) == 0)
			{
				LED_ON; // 这里是宏定义,GPIO_SetBits(GPIOA, GPIO_Pin_0);
			}
			else
			{
				LED_OFF; // 这里是宏定义,GPIO_ResetBits(GPIOA, GPIO_Pin_0);
			}
		}
	}
}

你可能感兴趣的:(STM32,stm32,单片机,嵌入式硬件)