Advertisement
pongfactory

Keypad ESL

Feb 25th, 2014
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.25 KB | None | 0 0
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // Author: RSP @KMUTNB
  3. // Date: 23-Oct-2013
  4. // Target Board: Arduino Uno (ATmega328P, 5V, 16MHz)
  5. // Arduino IDE: version 1.0.5
  6. // This sketch demonstrates how to do a keypad scan (a 4x4 keypad used)
  7. // (without use of the Keypad library).
  8.  
  9. // uncomment this line if you use Arduino Leonardo.
  10. //#define USE_LEONARDO
  11.  
  12. // constant values
  13. const byte BUZZER_PIN = 13;
  14. const byte ROWS = 4;
  15. const byte COLS = 4;
  16.  
  17. char keys[ROWS][COLS] = {
  18.   {'1','2','3','A'},
  19.   {'4','5','6','B'},
  20.   {'7','8','9','C'},
  21.   {'*','0','#','D'}
  22. };
  23.  
  24. byte rowPins[ROWS] = {2,3,4,5};   // connect D2,D3,D4,D5 to Rows 1-4 (the left four pins)
  25. byte colPins[COLS] = {8,9,10,11}; // connect D8,D9,D10,D11 to Column 1-4 (the right four pins)
  26.  
  27. void setup(){
  28.   Serial.begin( 115200 );
  29.   for (int i=0; i < ROWS; i++) {
  30.      pinMode( rowPins[i], OUTPUT );
  31.   }
  32.   for (int i=0; i < COLS; i++) {
  33.      pinMode( colPins[i], INPUT );
  34.      digitalWrite( colPins[i], HIGH ); // enable internal pull-up
  35.   }
  36.   pinMode( BUZZER_PIN, OUTPUT );
  37.   digitalWrite( BUZZER_PIN, LOW );
  38.  
  39. #ifdef USE_LEONARDO
  40.   delay(1000);
  41.   Keyboard.begin();
  42. #endif
  43. }
  44.  
  45. char getKey( ) {
  46.   char key_pressed = 0;
  47.   for (int j=0; j < ROWS; j++) { // scan the j-th row (j=0,1,2,3)
  48.     for (int i=0; i < ROWS; i++) {
  49.       // output HIGH to all rows, except the j-th row
  50.       digitalWrite( rowPins[i], (i==j) ? LOW : HIGH );
  51.     }
  52.     for (int i=0; i < COLS; i++) {
  53.       if ( digitalRead( colPins[i] ) == LOW ) { // Button at (R,C)=(j,i) is pressed
  54.          // wait until the button is released.
  55.          while ( digitalRead( colPins[i] ) != HIGH ) ; // blocking
  56.          key_pressed = keys[j][i]; // get the associated key for that button
  57.          break;
  58.       }
  59.     }  
  60.     digitalWrite( rowPins[j], HIGH );
  61.     if ( key_pressed != 0 ) {
  62.       return key_pressed;
  63.     }
  64.   }
  65.   return 0; // no key pressed
  66. }
  67.  
  68. void loop(){
  69.   char key = getKey();
  70.   if ( key != 0 ) {
  71.      digitalWrite( BUZZER_PIN, HIGH );
  72.  
  73. #ifdef USE_LEONARDO
  74.      Keyboard.press( key );
  75.      delayMicroseconds( 10 );
  76.      Keyboard.releaseAll();
  77. #endif
  78.  
  79.      Serial.println( key );
  80.      delay(50);
  81.      digitalWrite( BUZZER_PIN, LOW);
  82.   }
  83.   delay(10);
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement