代码
来源:蓝桥杯官方;
配置代码
#include "key.h"
void KEY_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_8;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1 | GPIO_Pin_2;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOB, &GPIO_InitStructure);
}
unsigned char KEY_Scan(void)
{
unsigned char ucKey_Val = 0;
if(~GPIO_ReadInputData(GPIOA) & 0x101)
{
Delay_KEY(10);
if(!GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0))
return 1;
if(!GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_8))
return 2;
}
else if(~GPIO_ReadInputData(GPIOB) & 6)
{
Delay_KEY(10);
if(!GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_1))
ucKey_Val = 3;
if(!GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_2))
ucKey_Val = 4;
}
return ucKey_Val;
}
void Delay_KEY(unsigned int ms)
{
unsigned int i, j;
for(i=0; i<ms; i++)
for(j=0; j<7992; j++);
}
应用代码
#include "key.h"
#include "led.h"
unsigned char ucLed = 1;
unsigned char ucKey_Long;
unsigned long ulTick_ms, ulKey_Time;
void KEY_Proc(void);
int main(void)
{
SysTick_Config(72000);
KEY_Init();
LED_Init();
BUZ_Init();
while(1)
{
KEY_Proc();
LED_Disp(ucLed);
}
}
void KEY_Proc(void)
{
unsigned char ucKey_Val;
ucKey_Val = KEY_Scan();
if(ucKey_Val != ucKey_Long)
{
ucKey_Long = ucKey_Val;
ulKey_Time = ulTick_ms;
}
else
ucKey_Val = 0;
if(ucKey_Val == 1)
{
ucLed <<= 1;
if(ucLed == 0) ucLed = 1;
}
if(ucKey_Val == 2)
{
ucLed >>= 1;
if(ucLed == 0) ucLed = 0x80;
}
if(ucKey_Long == 1)
{
if(ulTick_ms-ulKey_Time > 800)
{
ulKey_Time = ulTick_ms;
ucLed <<= 2;
if(ucLed == 0) ucLed = 1;
}
}
if(ucKey_Long == 2)
{
if(ulTick_ms-ulKey_Time > 800)
{
ucLed >>= 2;
if(ucLed == 0) ucLed = 0x80;
}
}
if(ucKey_Long == 3)
GPIO_ResetBits(GPIOB, GPIO_Pin_4);
else
GPIO_SetBits(GPIOB, GPIO_Pin_4);
}
void SysTick_Handler(void)
{
ulTick_ms++;
}
快速配置
打开库文件里官方外设例程,找到GPIO—— 在IOToggle" 文件夹下,打开 “main.c”—— 基础配置直接复制粘贴,然后修改引脚;
剩下的就自己背吧 hhhh.
|