值得注意的是,独立按键的检测原理和消抖处理在51单片机中已经讲过了,这些东西都不会变。只是AVR单片机的IO口操作方式改变了。在AVR中,检测方式是:首先让将和独立按键相连接的IO口设置成输出高电平,接着将他们设置成输入模式,再然后检测这些IO口的值。电路图如下所示。
代码1:检测是哪一个按键被按下。这里不需要用到消抖动处理。
#include<iom16v.h>
#include<macros.h>
#define uint unsigned int
#define uchar unsigned char
uchar table[] = {0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80};
void keyScan();
void initSYS();
void main()
{
initSYS();
while(1)
{
keyScan();
}
}
void initSYS()
{
//init the system
DDRB = 0xFF;
PORTB = 0xFF;
DDRA = 0xFF;
PORTA = table[0];
}
void keyScan()
{
//to check wether the key has pressed
uchar isPressed;
DDRB = 0x00;
isPressed = PINB;
if(isPressed != 0xFF)
{
switch(isPressed)
{
case 0x7F:
PORTA = table[1];
break;
case 0xBF:
PORTA = table[2];
break;
case 0xDF:
PORTA = table[3];
break;
case 0xEF:
PORTA = table[4];
break;
case 0xF7:
PORTA = table[5];
break;
case 0xFB:
PORTA = table[6];
break;
case 0xFD:
PORTA = table[7];
break;
case 0xFE:
PORTA = table[8];
break;
}
}
else
{
//PORTA = table[0];
}
}代码2:每次按一下按键,数字就加1。
#include<iom16v.h>
#include<macros.h>
#define uint unsigned int
#define uchar unsigned char
uchar table[] = {0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};
uchar num;
void init();
void delay();
void keyScan();
void main()
{
init();
while(1)
{
keyScan();
}
}
void init()
{
DDRA = 0xFF;
PORTA = table[0];
DDRB = 0xFF;
PORTB = 0xFF;
num = 0;
}
void keyScan()
{
uchar keyValue;
DDRB = 0x00;
keyValue = PINB;
if(keyValue == 0xFE)
{
delay();
if(keyValue == 0xFE)
{
delay();
num++;
if(num == 10)
{
num = 0;
}
PORTA = table[num];
}
}
}
void delay()
{
uint i,j;
for(i=0;i<100;i++)
for(j=0;j<100;j++);
}原文地址:http://blog.csdn.net/kotei_88_luluc_66/article/details/41315543