/* p3_4.c: Matrix keypad detect * * This program checks a 4x4 matrix keypad to see whether * a key is pressed or not. When a key is pressed, it turns * on the blue LED. * * Port4 7-4 are connected to the columns and Port4 3-0 are connected * to the rows of the keypad. * * Tested with Keil 5.20 and MSP432 Device Family Pack V2.2.0. */ #include "msp.h" void delay(void); void keypad_init(void); char keypad_kbhit(void); int main(void) { keypad_init(); P2->DIR = 0x04; /* make blue LED pins output */ while(1) { if (keypad_kbhit() != 0) /* if a key is pressed */ P2->OUT |= 0x04; /* turn on blue LED */ else P2->OUT &= ~0x04; /* turn off blue LED */ } } /* this function initializes Port 4 that is connected to the keypad. * All pins are configured as GPIO input pin. The column pins have * the pull-up resistors enabled. */ void keypad_init(void) { P4->DIR = 0; P4->REN = 0xF0; /* enable pull resistor for column pins */ P4->OUT = 0xF0; /* make column pins pull-ups */ } /* This is a non-blocking function. * If a key is pressed, it returns 1. * Otherwise, it returns a 0 (not ASCII '0'). */ char keypad_kbhit(void) { int col; P4->DIR |= 0x0F; /* make all row pins output */ P4->OUT &= ~0x0F; /* drive all row pins low */ delay(); /* wait for signals to settle */ col = P4->IN & 0xF0; /* read all column pins */ P4->DIR &= ~0x0F; /* disable all row pins drive */ if (col == 0xF0) /* if all columns are high */ return 0; /* no key pressed */ else return 1; /* a key is pressed */ } /* make a small delay */ void delay(void) { }