avrstudio 5 矩阵键盘

关键点:

先给PC口的低4为为输出高4位为输入,来判断是那一列,后交叉来赋值来判断是那一行

源代码:

#include <avr/io.h>
#include<util/delay.h>
#define F_CPU 8000000UL

const unsigned char table[]=
{
  0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,
  0x7F,0x6F,0x77,0x7C,0x39,0x5E,0x79,0x71
};
char key_num;
unsigned char check();
void key_scan();
void beep();
int main(void)
{
    DDRE=0xff;
    while(1)
    {
      if(check())
        key_scan();
       else
       continue;
       if (key_num<16)
       {
           PORTE=table[key_num];
           beep();
       }
    }
}

void beep()
{
    int i;
    for (i=0;i<10;i++)
    {
        PORTF=0x04;
        _delay_ms(1);
        PORTF=0x00;
    }
}

void key_scan()
{
    switch(PINC)
    {
        case 0x0e: key_num=0;break;
        case 0x0d: key_num=1;break;
        case 0x0b: key_num=2;break;
        case 0x07: key_num=3;break;
        default:key_num=0xff;       
    }
    DDRC=0x0f;PORTC=0xf0;_delay_ms(4);
    switch(PINC)
    {
        case 0xe0:     key_num+=0;break;
        case 0xd0:     key_num+=4;break;
        case 0xb0:     key_num+=8;break;
        case 0x70:     key_num+=12;break;
        default:key_num=0xff;   
    }
}

unsigned char check()
{
    DDRC=0xf0;PORTC=0x0f;_delay_ms(4);
    return    PINC!=0x0f ? 1:0;   
}

 

截图:

2011-3-26-17-34

你可能感兴趣的:(IO)