用电阻分压做的ad键盘,优点就是一个IO口可以做很多按键,缺点是长期稳定性较差。驱动源码如下:
#include <mega16.h>
#include <delay.h>
//以下为AD键盘扫描部分
#define ADC_VREF_TYPE 0x60 //内部2.56V参考电压
flash uchar Key_Num[16]={14,25,37,48,57,68,78,88,99,112,124,139,156,174,196,223};
bit juder=0;
/*---------------AD转换程序---------------*/
unsigned char read_adc(unsigned char adc_input)
{
ADMUX=adc_input | (ADC_VREF_TYPE & 0xff);
// Start the AD conversion
ADCSRA|=0x40;
// Wait for the AD conversion to complete
while ((ADCSRA & 0x10)==0);
ADCSRA|=0x10;
return ADCH;
}
/*-------------键盘扫描程序-------------*/
uchar Key_Scan(void)
{
uchar i,t,temp=0;
for(i=0;i<4;i++)//扫描四次,取最大值
{
t=read_adc(0);
if(t>temp)temp=t;
}
if(temp>5)for(i=0;i<16;i++)//键值有效性判断
{
if(temp>Key_Num)t=temp-Key_Num;
else t=Key_Num-temp;
if(t<5&&juder){juder=0;return i;} //返回键值
t=0;
}
else juder=1;//判断按键是否松开
return 16;//未得到任何键值
}
/*-------------数码管显示程序-------------*/
void display(unsigned char number,unsigned char position)//digtial show function
{
DDRB=0Xff;//set PORTA output
 ORTB=0XFF;//set PORTA output in high level
switch(position)//choice the position
{
case 1:{PORTB&=0xf8;break;}
case 2:{PORTB&=0xf9;break;}
case 3:{PORTB&=0Xfa;break;}
case 4:{PORTB&=0Xfb;break;}
case 5:{PORTB&=0Xfc;break;}
case 6:{PORTB&=0Xfd;break;}
case 7:{PORTB&=0Xfe;break;}
case 8:{PORTB&=0Xff;break;}
}
switch(number)//show number
{
case 0:{PORTB&=0x87;break;} //0
case 1:{PORTB&=0x8f;break;} //1
case 2:{PORTB&=0x97;break;} //2
case 3:{PORTB&=0x9f;break;} //3
case 4:{PORTB&=0xa7;break;} //4
case 5:{PORTB&=0xaf;break;} //5
case 6:{PORTB&=0xb7;break;} //6
case 7:{PORTB&=0xbf;break;} //7
case 8:{PORTB&=0xc7;break;} //8
case 9:{PORTB&=0xcf;break;} //9
default:{PORTB=0xff;break;} //null
}
}
void main(void)
{
unsigned char b1,b2,b3,b4;
unsigned char k=0;
uint t=0;
ADMUX=ADC_VREF_TYPE & 0xff;
ADCSRA=0x83;
while(1)
{
b1=t%10;display(b1,8);delay_us(1000);
b2=(t/10)%10;display(b2,7);delay_us(1000);
b3=(t/100)%10;display(b3,6);delay_us(1000);
b4=(t/1000)%10;display(b4,5);delay_us(1000);
k=Key_Scan();
if(k<16)
{
t=t*10;
t+=k;
}
if(t>9999)t=0;
}
}
|