#define F_CPU 16000000
#include <avr/io.h> //standard AVR header
#include <util/delay.h> //delay header
#define KEY_PRT PORTK //keyboard PORT
#define KEY_DDR DDRK //keyboard DDR
#define KEY_PIN PINK //keyboard PIN
void usart_init (void) {
UCSR0B = (1 << TXEN0); // TX enabled
// Asynchronous USART, no parity, 1-bit stop, 8-bit data
UCSR0C = (1 << UCSZ01) | (1 << UCSZ00);
// (Fosc / 16 (baud rate)) – 1
// (16e6 / (16*9600)) – 1 = 103.17 ~ 103 = 0x67
UBRR0L = 0x67;
}
void usart_send (unsigned char ch) {
while (!(UCSR0A & (1 << UDRE0)));
UDR0 = ch;
}
unsigned char keypad[4][4] = {
'1','2','3','A',
'4','5','6','B',
'7','8','9','C',
'*','0','#','D'
};
int main(void) {
unsigned char colloc, rowloc;
//keyboard routine. This sends the ASCII
//code for pressed key to port c
DDRB = 0xFF;
KEY_DDR = 0xF0; //
KEY_PRT = 0xFF;
usart_init();
while (1) //repeat forever
{
do {
KEY_PRT &= 0x0F; //ground all rows at once
colloc = (KEY_PIN & 0x0F); //read the columns
} while (colloc != 0x0F); //check until all keys released
do {
do {
_delay_ms(20); //call delay
colloc = (KEY_PIN & 0x0F); //see if any key is pressed
} while (colloc == 0x0F); //keep checking for key press
_delay_ms(20); //call delay for debounce
colloc = (KEY_PIN & 0x0F); //read columns
} while (colloc == 0x0F); //wait for key press
while (1) {
KEY_PRT = 0xEF; //ground row 0
colloc = (KEY_PIN & 0x0F); //read the columns
if (colloc != 0x0F) //column detected
{
rowloc = 0; //save row location
break; //exit while loop
}
KEY_PRT = 0xDF; //ground row 1
colloc = (KEY_PIN & 0x0F); //read the columns
if (colloc != 0x0F) //column detected
{
rowloc = 1; //save row location
break; //exit while loop
}
KEY_PRT = 0xBF; //ground row 2
colloc = (KEY_PIN & 0x0F); //read the columns
if (colloc != 0x0F) //column detected
{
rowloc = 2; //save row location
break; //exit while loop
}
KEY_PRT = 0x7F; //ground row 3
colloc = (KEY_PIN & 0x0F); //read the columns
rowloc = 3; //save row location
break; //exit while loop
}
//check column and send result to Port D
if (colloc == 0x0E) {
// PORTB = (keypad[rowloc][0]);
usart_send(keypad[rowloc][0]);
} else if (colloc == 0x0D) {
// PORTB = (keypad[rowloc][1]);
usart_send(keypad[rowloc][1]);
} else if (colloc == 0x0B) {
// PORTB = (keypad[rowloc][2]);
usart_send(keypad[rowloc][2]);
}
else {
// PORTB = (keypad[rowloc][3]);
usart_send(keypad[rowloc][3]);
}
}
return 0;
}