How to call functions when a key changes it's state

Dependencies:   Hotboards_keypad mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 
00002 #include "mbed.h"
00003 #include "Hotboards_keypad.h"
00004 
00005 // Defines the keys array with it's respective number of rows & cols,
00006 // and with the value of each key
00007 char keys[ 4 ][ 4 ] =
00008 {
00009     { '1' , '2' , '3' , 'A' },
00010     { '4' , '5' , '6' , 'B' },
00011     { '7' , '8' , '9' , 'C' },
00012     { '*' , '0' , '#' , 'D' }
00013 };
00014 
00015 // Defines the pins connected to the rows
00016 DigitalInOut rowPins[ 4 ] = { PA_6 , PA_7 , PB_6 , PC_7 };
00017 // Defines the pins connected to the cols
00018 DigitalInOut colPins[ 4 ] = { PA_8 , PB_10 , PB_4 , PB_5 };
00019 
00020 // Creates a new keyboard with the values entered before
00021 Keypad kpd( makeKeymap( keys ) , rowPins , colPins , 4 , 4 );
00022 
00023 // Configures the serial port
00024 Serial pc( USBTX , USBRX );
00025 
00026 // For this example we will use the Nucleo LED1 on pin PA_5
00027 DigitalOut led1( LED1 );
00028 bool blink = false;
00029 bool ledPin_state;
00030 
00031 
00032 // Taking care of some special events.
00033 void kpdEvent( KeypadEvent key )
00034 {
00035     switch( kpd.getState( ) )
00036     {
00037         case PRESSED:
00038             if( key == '#' )
00039             {
00040                 led1 = !led1;
00041                 ledPin_state = led1; // Remember LED state, lit or unlit.
00042             }
00043             break;
00044         case RELEASED:
00045             if( key == '*' )
00046             {
00047                 led1 = ledPin_state;
00048                 blink = false; // Restore LED state from before it started blinking.
00049             }
00050             break;
00051         case HOLD:
00052             if( key == '*' )
00053             {
00054                 blink = true; // Blink the LED when holding the * key.
00055             }
00056             break;
00057     }
00058 }
00059 
00060 int main()
00061 {
00062     led1 = 1; // Turn the LED on.
00063     ledPin_state = led1; // Store initial LED state. HIGH when LED is on.
00064     kpd.addEventListener( kpdEvent ); // Add an event listener for this keypad
00065     while(1)
00066     {
00067         char key = kpd.getKey( );
00068         if( key )
00069         {
00070             pc.printf( "%c" , key );
00071         }
00072         if( blink )
00073         {
00074             led1 = !led1; // Change the ledPin from Hi2Lo or Lo2Hi
00075             wait_ms( 100 );
00076         }
00077     }
00078 }