码迷,mamicode.com
首页 > 其他好文 > 详细

AVR第8课:独立按键

时间:2014-11-20 18:52:52      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:avr   单片机   独立按键消抖动   

值得注意的是,独立按键的检测原理和消抖处理在51单片机中已经讲过了,这些东西都不会变。只是AVR单片机的IO口操作方式改变了。在AVR中,检测方式是:首先让将和独立按键相连接的IO口设置成输出高电平,接着将他们设置成输入模式,再然后检测这些IO口的值。电路图如下所示。

bubuko.com,布布扣

代码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++);
}



AVR第8课:独立按键

标签:avr   单片机   独立按键消抖动   

原文地址:http://blog.csdn.net/kotei_88_luluc_66/article/details/41315543

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!