/* * Keyboard.c * * Created: 5.6.2014 16:45:06 * Author: maticpi */ #include void Init(); char GetKey(); //returns the last key that was pressed, 0 if no key was pressed void ReadKBD(); //Checks the state of IO ports to determine if a key was pressed char lastkey; //global variable, which holds the value of the last key that was pressed int main(void) { char cmd; Init(); while(1) { ReadKBD(); //call this function once every 1 to 10 ms to prevent false detections due to key bouncing cmd=GetKey(); //get the value of the last key pressed switch (cmd) { case 1: PORTB++; break; //do this for key 1 case 2: PORTB--; break; //do this for key 2 case 3: PORTB = 0; break; //do this for key 3 case 4: PORTD ^= 0x80; break; //do this for key 4 default: break; //don't do anything if no key was pressed } } } void ReadKBD() { static char oldD; //holds the old value of the keyboard IO port char newD=(PIND>>2) & 0x0F; //get the new value of the IO port (keys are connected to PD2, PD3, PD4 and PD5) char pressed = (newD ^ oldD) & oldD; //if the port state has changed, and the old value was 1, the key was pressed if (pressed & 0x01) lastkey=1; //if the corresponding bit in variable "pressed" is one, then that key was pressed if (pressed & 0x02) lastkey=2; // (lastkey can only hold one value, therefore if more than one key was pressed if (pressed & 0x04) lastkey=3; // at once, one event will be lost) if (pressed & 0x08) lastkey=4; oldD=newD; //update the } char GetKey() { char tmp=lastkey; lastkey=0; return tmp; } void Init() { //IO port PORTA=0x08; //0000 1000 PORTB=0x00; //0000 0000 PORTC=0x3E; //0011 1110 PORTD=0x7D; //0111 1101 //1-output, 0-input DDRA=0xF0; //1111 0000 DDRB=0xFF; //1111 1111 DDRC=0xC1; //1100 0001 DDRD=0x82; //1000 0010 }