#include <avr/io.h>
#include <avr/delay.h>
#include <avr/interrupt.h>
void Uart_Init(void);
unsigned char Getchar(void);
void Putchar(unsigned char c);
unsigned char Read_Key(void);
void Disp(void);
unsigned char KeyNumber;
unsigned char string[8]={10,10,10,10,10,10,10,10};
unsigned char Disp_Buff[11] = {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x00};
int main(void)
{
TIMSK |= (1 << TOIE0);
TCCR0 |= (1 <<CS02);
TCNT0 = 50;
sei();
DDRA=0xff;
DDRB=0xff;
KeyNumber=0xff;
unsigned char i=0xff,t;
Uart_Init();
while(1)
{
// Disp();
i=Read_Key();
if(i==0)continue;
if(i==2)
{
for(t=0;t<8;t++)string[t]=10;
} //清除
if(i==3)
{
for(t=0;t<8;t++)Putchar(string[t]);
} //发送
if(i==1)
{
for(t=0;t<7;t++)string[t]=string[t+1];
string[7]=KeyNumber;
}
}
}
void Uart_Init(void)
{
UCSRB = 0x00; //disable while setting baud rate
UCSRA = 0x00; //Bit1为1则倍速发送
UCSRC = 0x86;
UBRRL = 0x33; //波特率:9600 Bps
UBRRH = 0x00; //误差率:0.156%
UCSRB = 0x18;
}
unsigned char Getchar(void)
{
while(!(UCSRA& (1<<RXC)));
return UDR;
}
void Putchar(unsigned char c)
{
while (!(UCSRA&(1<<UDRE)));
UDR=c;
}
unsigned char Read_Key(void)
{
unsigned char i,j;
DDRC = 0xf0; //设置PD高四位为输出口,低四位为输入口
PORTC = 0x00; // 初始运行输出全为0
if((PINC & 0x0f) == 0x0f) return 0; // 判断有无按键动作,没有,返回0
else
{
_delay_ms(1); //按键消抖
if((PINC & 0x0f) == 0x0f) return 0; //再次判断是否有按键动作
else
{
for(i = 4;i < 8;i++) //逐行输出0
{
PORTC = ~(1 << i) | 0x0f; //第i行输出0
for(j = 0;j < 4;j++)
{
if((PINC & (1 << j)) == 0) //逐列检测
KeyNumber = (i - 4) * 3 + j+1;
if(KeyNumber==11)KeyNumber=0; //计算键值
}
}
DDRC = 0xf0; //设置PD高四位为输出口,低四位为输入口
PORTC = 0x00;
while((PINC & 0x0f) != 0x0f);//等待按键完成
if(KeyNumber==10)return 2; //按键为“*”
if(KeyNumber==12)return 3; //按键为“#”
return 1;
}
}
}
void Disp(void)
{
unsigned char i;
for(i=0;i<8;i++)
{
PORTA=~(1<<i);
PORTB=Disp_Buff[string[i]];
_delay_ms(1);
}
PORTA=0xff;
}
ISR(TIMER0_OVF_vect )
{
TCNT0 = 50;
Disp();
}