1; Hardware;
prepare a 2*2 matrix keyboard, connect to PB8,
9 , 10, 11 respectively; 2; matrix keyboard principle;
let pa8, 9 output high level, pa10, 11 input; when pa10, 11 detects high At the level, the value of i is obtained. Then flip, let pa8,9 input, pa10,11 output high level; when high level is detected in pa8,9, get the value of j; then determine which button is through i,j;
3; keyboard.c function implementation;
在这里插入代码片
#include "keyboard.h"
#include "stm32f10x.h"
#include "delay.h"
#include "usart.h"
#include "led.h"
u8 key_scan(void)
{
u8 i=0,j=0;
uart_init(72,9600);//串口时钟,波特率设置;
//开启时钟
RCC->APB2ENR |=1<<3;
//端口模式配置
GPIOB->CRH &=0XFFFF0000;
GPIOB->CRH |=0X00003388;
//关闭端口
GPIOB->ODR &=~(1<<8);
GPIOB->ODR &=~(1<<9);
GPIOB->ODR &=~(1<<10);
GPIOB->ODR &=~(1<<11);
//高低电平配置
PBout(10)=1;
PBout(11)=1;
PBin(8)=0;
PBin(9)=0;
//清零
i=0,j=0;
//检测电平变化
if(PBin(8)==1 || PBin(9)==1)
{
delay_ms(10);
if(PBin(8)==1 )
i=1;
if(PBin(9)==1 )
i=2;
}
else
{
return 0;
}
//同上
GPIOB->CRH &=0XFFFF0000;
GPIOB->CRH |=0X00008833;
GPIOB->ODR &=~(1<<10);
GPIOB->ODR &=~(1<<11);
GPIOB->ODR &=~(1<<8);
GPIOB->ODR &=~(1<<9);
PBout(8)=1;
PBout(9)=1;
PBin(10)=0;
PBin(11)=0;
if(PBin(10)==1 || PBin(11)==1)
{
delay_ms(10);
if(PBin(10)==1) j=1;
else if(PBin(11)==1)
j=2;
}
else
return 0;
//通过i,j值确定按键位置
if(i==1 && j==1)
return 1;
else if(i==1 && j==2)
return 2;
else if(i==2 && j==1)
return 3;
else if(i==2 && j==2)
return 4;
else
return 0;
}
4: Implementation of keyboard.h function;
在这里插入代码片
#ifndef _KEYBOARD_H_
#define _KEYBOARD_H_
#include "sys.h"
u8 key_scan(void);
#endif
5: Main function realization;
在这里插入代码片
int main(void)
{
u8 h;//接收返回值
Stm32_Clock_Init(9);//PLL倍频设置系统时钟
delay_init(72);//延迟函数时钟
uart_init(72,9600);//串口初始化
LED_Init();//led初始化
while(1)
{
h=key_scan();//获取返回值
LED0=0;//检测程序是否运行
switch(h)//串口输出按键位置
{
case 1:printf("按键1\r\n");delay_ms(1000);break;
case 2:printf("按键2\r\n");delay_ms(1000);break;
case 3:printf("按键3\r\n");delay_ms(1000);break;
case 4:printf("按键4\r\n");delay_ms(1000);break;
default :printf("无按键按下\r\n");delay_ms(1000);break;
}
}
}
Please correct me if there are any errors! ! !