新聞中心

EEPW首頁 > 嵌入式系統(tǒng) > 設(shè)計(jì)應(yīng)用 > Stm32矩陣鍵盤掃描程序分析

Stm32矩陣鍵盤掃描程序分析

作者: 時(shí)間:2016-11-27 來源:網(wǎng)絡(luò) 收藏
我們知道在51單片機(jī)中,通過掃描某個(gè)口的電平高低得知那個(gè)按鍵按下,比如,控制兩行4列,

本文引用地址:http://butianyuan.cn/article/201611/322269.htm

假如讓P1=0xCf;低位都置1(pb0-pb3),pb4-pb5置0;然后我們就掃描P1口就行了,如果有按鍵被按下的,高電平會(huì)被強(qiáng)制拉低的。

假如按鍵返回的值為0xce,可知是pb0被拉低了,由此可判斷是S1或者S2按下了,其他的同理。

當(dāng)然只讓P1=0xcf,是不能判斷出具體的按鍵是哪個(gè)的,此時(shí),如果我們?nèi)》醇萈1=0x30;

當(dāng)按鍵返回值為0x10時(shí),我們可得知01 0000,pb5=0,s1或者s2被按下,這個(gè)時(shí)候我們將0xce|0x10=0xde,就是唯一的值了。以此類推,得出其他的值來。

在stm32中是同樣的大道理;

uint8_t KeyScan(void)

{

uint8_t HangValue = 0;

uint8_t LieValue= 0;

uint16_t KeyValue= 0;

uint8_t Tmp =0;

static uint8_t KeyConter = 0;

GPIO_SetBits(Colum1.port, (Colum1.pin|Colum2.pin|Colum3.pin|Colum4.pin));

GPIO_ResetBits(Line1.port,(Line1.pin|Line2.pin));

Tmp = GPIO_ReadInputData(Line1.port);

if ((Tmp&0x0F) != 0x0F)

{

if (KeyConter < 1)

{//去抖

KeyConter++;

}

else

{

HangValue = Tmp&0x0f;

GPIO_ResetBits(Colum1.port, (Colum1.pin|Colum2.pin|Colum3.pin|Colum4.pin));

GPIO_SetBits(Line1.port,(Line1.pin|Line2.pin));

Tmp = GPIO_ReadInputData(Colum1.port);

LieValue = Tmp&0x30;

KeyValue = (HangValue)|LieValue;

if (KeyValue)// KeyValue^KeyValueBkp

{

KeyValueBkp = KeyValue;

switch (KeyValue)

{

//case KEY_10:return KEY_NUM_0;//16;----0

case KEY_01:return KEY_NUM_1;//3;-----1

case KEY_02:return KEY_NUM_2;//4;-----2

case KEY_03:return KEY_NUM_3;//5;-----3

case KEY_04:return KEY_NUM_4;//7;-----4

case KEY_05:return KEY_NUM_5;//8;-----5

case KEY_06:return KEY_NUM_6;//9;-----6

case KEY_07:return KEY_NUM_7;//11----7

case KEY_08:return KEY_NUM_8;//------8

default:

return 0;

}

}

else

{

return 0;

}

}

}

else

{

KeyConter = 0;//計(jì)數(shù)清零

KeyValueBkp = 0;

}

return 0;

}

typedef struct

{

GPIO_TypeDef*port;

uint16_tpin;

}Matrix_t;

//const Matrix_t Colum1 = {GPIOD, GPIO_PIN_2};

//const Matrix_t Colum2 = {GPIOD, GPIO_PIN_3};

//const Matrix_t Colum3 = {GPIOD, GPIO_PIN_4};

const Matrix_t Colum1 = {GPIOB, GPIO_Pin_0};

const Matrix_t Colum2 = {GPIOB, GPIO_Pin_1};

const Matrix_t Colum3 = {GPIOB, GPIO_Pin_2};

const Matrix_t Colum4 = {GPIOB, GPIO_Pin_3};

const Matrix_t Line1= {GPIOB, GPIO_Pin_4};

const Matrix_t Line2= {GPIOB, GPIO_Pin_5};

#define KEY_01 0x1e

#define KEY_02 0x2e

#define KEY_03 0x1d

#define KEY_04 0x2d

#define KEY_05 0x1b

#define KEY_06 0x2b

#define KEY_07 0x17

#define KEY_08 0x27



關(guān)鍵詞: Stm32矩陣鍵盤掃描程

評(píng)論


技術(shù)專區(qū)

關(guān)閉