EventKeypad.ino (1942B)
1 /* @file EventSerialKeypad.pde 2 || @version 1.0 3 || @author Alexander Brevig 4 || @contact alexanderbrevig@gmail.com 5 || 6 || @description 7 || | Demonstrates using the KeypadEvent. 8 || # 9 */ 10 #include <Keypad.h> 11 12 const byte ROWS = 4; //four rows 13 const byte COLS = 3; //three columns 14 char keys[ROWS][COLS] = { 15 {'1','2','3'}, 16 {'4','5','6'}, 17 {'7','8','9'}, 18 {'*','0','#'} 19 }; 20 21 byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad 22 byte colPins[COLS] = {8, 7, 6}; //connect to the column pinouts of the keypad 23 24 Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS ); 25 byte ledPin = 13; 26 27 boolean blink = false; 28 boolean ledPin_state; 29 30 void setup(){ 31 Serial.begin(9600); 32 pinMode(ledPin, OUTPUT); // Sets the digital pin as output. 33 digitalWrite(ledPin, HIGH); // Turn the LED on. 34 ledPin_state = digitalRead(ledPin); // Store initial LED state. HIGH when LED is on. 35 keypad.addEventListener(keypadEvent); // Add an event listener for this keypad 36 } 37 38 void loop(){ 39 char key = keypad.getKey(); 40 41 if (key) { 42 Serial.println(key); 43 } 44 if (blink){ 45 digitalWrite(ledPin,!digitalRead(ledPin)); // Change the ledPin from Hi2Lo or Lo2Hi. 46 delay(100); 47 } 48 } 49 50 // Taking care of some special events. 51 void keypadEvent(KeypadEvent key){ 52 switch (keypad.getState()){ 53 case PRESSED: 54 if (key == '#') { 55 digitalWrite(ledPin,!digitalRead(ledPin)); 56 ledPin_state = digitalRead(ledPin); // Remember LED state, lit or unlit. 57 } 58 break; 59 60 case RELEASED: 61 if (key == '*') { 62 digitalWrite(ledPin,ledPin_state); // Restore LED state from before it started blinking. 63 blink = false; 64 } 65 break; 66 67 case HOLD: 68 if (key == '*') { 69 blink = true; // Blink the LED when holding the * key. 70 } 71 break; 72 } 73 }