How to Use Keypad Arduino Easy With Servomotor
A keypad is a useful feature to add to a project that requires data input. Today we will see how easy it is to use an inexpensive matrix membrane keypad with an Arduino.
We'll see how the keypad works, check out a library that makes using the keypad very easy, and we'll even construct an electronic combination lock.
Introduction
One of the simplest interfaces for an Arduino project is a push button switch. It can easily be added by connecting one side of the switch to ground and the other side to one of the Arduino's digital input pins. Hold the input pin HIGH, either by using a resistor or the microcontroller's internal pullup, and that's all you need. Pressing the button will send the input pin LOW, and you can detect this change within your sketch to provide functionality for the push button.
Expanding the number of push buttons just requires you to repeat this process using different input pins. Simple, but it does present some design problems:
- One wire, plus a ground connection, for every push button can add up to a lot of wiring.
- It adds to the complexity of your sketch. Well perhaps "complexity" is an exaggeration, but it does require more code!
- Eventually, you'll run out of input pins on your Arduino, especially if you are not using a Mega 2560.
There are a couple of better ways to add a number of push button switches to your project.
Add an ASCII Keyboard
This is the ultimate solution. You can add a full 101-key keyboard to your project using the serial input connection. This will allow for very complex data entry, while using a minimal number of inputs on the Arduino. You can even respond to events that require two (or three) keys to be pressed simultaneously.
But doing this is usually overkill if all you need is a numeric input, such as for a combination lock or a settings panel.
Add a Resistive Keypad
This is a really elegant solution, and it only takes one analog input.
With this arrangement, a group of push buttons are connected to different points within a resistor array, that itself is connected between the reference voltage and ground.
When a push button is activated it causes a voltage to be sent to the analog input. As each push button is on a different leg of the array it will have a unique corresponding voltage. Your sketch can read the value of the A/D converter and use it to determine which button was activated.
This is a good solution for applications that only require a few push buttons, add too many buttons and you run the risk of inaccuracies due to reference voltage fluctuations or resistor tolerances.
But it certainly is a viable choice, and we have used it before in the article about using LCD displays. The LCD display shield has a group of push buttons wired up in this exact fashion.
Add a Matrix Keypad
This is the solution we will look at today.
A matrix keypad is a group of switches connected in an X-Y, or row-column, matrix arrangement. Pressing a button will connect a row with a column, and we can then scan the array to determine which button was pressed.
By arranging the push buttons in a matrix as opposed to connecting them directly to input pins we can usually reduce the amount of wiring. Commercial matrix keypads are inexpensive and readily available, which simplifies the wiring even more.
This is a great solution, with the following caveats:
- You need at least six pushbuttons. Fewer than six defeats the wiring advantages, as six pushbuttons will require a 2 x 3 matrix for a total of five wires. A larger number of keys will increase the advantage of using a matrix.
- You don't require users to press two buttons simultaneously. The keypad solution will only accept one input at a time.
- You'll need to use a software routine to determine which button was pressed, this is in addition to the code you'll need to write to actually do something once the keypress is received.
- You'll still need a lot of inputs, not as many as discrete switches (providing you stay over five) but more than the resistive keypad or ASCII keyboard solutions. Once you exceed 25 push buttons you're better off choosing the ASCII Keyboard solution.
In many cases, the matrix keypad still has a lot of advantages. And that's what we will be using in our experiments today.
Matrix Membrane Keypads
The type of keypad we will be using today is a "Matrix Membrane Keypad". This is an X-Y matrix of switches created using layers of plastic and conductive surfaces. These devices are inexpensive and can be styled to match your project, reducing the mechanical work of mounting all of those push buttons.
Two extremely common membrane matrix keypads are the 4 x 3 keypad (12 switches) and the 4 x 4 keypad (16 switches). They are laid out in the same fashion as a telephone keypad, which is a common user interface that most people are familiar with.
Although I'll be using the 4 X 4 matrix keypad in today's experiments you can easily substitute the 4 x 3 unit with minor wiring and code changes.
How Matrix Keypads Work
To understand how matrix keypads work we'll examine the operation of a basic 4 x 4 keypad.
As you can see from the above illustration the keypad consists of four rows and four columns, overlaid by 16 push button switches (represented by circles). Pressing a switch will connect its corresponding row and column lines.
In order to use the keypad we will make all of the column connections inputs and hold them HIGH, so they all have a value of digital one. The rows are configured as outputs, each with a value of zero or LOW.
When a key is pressed, as illustrated above, it will connect its column input to one of the row outputs. This will bring that input LOW, and in doing so it reveals which column the switch belongs to. It also serves as an indication that a switch was pressed.
Now we need to determine which row the switch is connected to. To do this we will pull all of the column inputs LOW (technically we really only need to keep our detected column LOW, but it is simpler to control them all).
After doing this we begin scanning the rows by raising them HIGH, one-by-one. In the above illustration, we test the top row, which produces no results.
Scanning the second row by bringing it HIGH also produces no results.
The third row, however, is the correct row. Bringing it HIGH will cause the column output to go HIGH, revealing the location of the switch.
While the above steps may at first appear complex they actually are not. We will be using a common library to do all of the work for us.
Inexpensive Membrane Matrix Keypads
The keypad we will be using in our experiments is very inexpensive and easily available. It consists of four rows and four columns, each connected to a film ribbon cable.
The film ribbon cables both terminate with an 8-pin female Dupont connector. The pinouts are as follows:
- Row 1
- Row 2
- Row 3
- Row 4
- Column 1
- Column 2
- Column 3
- Column 4
If you obtain a 4 x 3 keypad you can use it in the experiments, the only difference is that it will have a 7-pin connector and will be missing the Column 4 connection.
Now that you understand how the keypad works let's see how to use it with an Arduino.
Basic Keypad Test
The first experiment we'll perform with the keypad is to simply connect it up to the Arduino and use the serial monitor to verify that we can read all of the keys. This is a good way to get to know how to work with the keypad, and can also be used to verify that all of the keys are indeed working.
Keypad Test Hookup
The hookup of the keypad and the Arduino is shown below:
The easiest way to get everything connected is to use a multi-conductor male-to-male Dupont ribbon cable with 8 conductors. The hookup is quite simple, as the Arduino connections are all made in the same order as they are on the keypad connector.
Once everything is hooked up you can proceed to the sketch that we'll use to test our keypad.
Keypad Test Sketch
The sketch we'll be using is simplified by the use of a special library, the Keypad Library by Mark Stanley and Alexander Brevig . With this library using matrix keypads is very easy.
You can install this library directly from your Library Manager.
- Open your Arduino IDE.
- Select the Sketch item from the top menu bar.
- Navigate to Include Library. A sub-menu will open.
- Select Manage Libraries . This will open the Library Manager dialog box.
- In the Filter Your Search box type "keypad".
- From the results scroll down until you find the Keypad by Mark Stanley and Alexander Brevig library.
- Select Install to install the library
- Close the Library Manager dialog box.
Once you have this library installed you can enter the following sketch:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | /* Matrix Keypad Demo keypad-demo.ino Demonstrates use of 4x4 matrix membrane keypad with Arduino Results on serial monitor DroneBot Workshop 2020 https://dronebotworkshop.com */ // Include the Keypad library #include <Keypad.h> // Constants for row and column sizes const byte ROWS = 4 ; const byte COLS = 4 ; // Array to represent keys on keypad char hexaKeys [ ROWS ] [ COLS ] = { { '1' , '2' , '3' , 'A' } , { '4' , '5' , '6' , 'B' } , { '7' , '8' , '9' , 'C' } , { '*' , '0' , '#' , 'D' } } ; // Connections to Arduino byte rowPins [ ROWS ] = { 9 , 8 , 7 , 6 } ; byte colPins [ COLS ] = { 5 , 4 , 3 , 2 } ; // Create keypad object Keypad customKeypad = Keypad ( makeKeymap ( hexaKeys ) , rowPins , colPins , ROWS , COLS ) ; void setup ( ) { // Setup serial monitor Serial . begin ( 9600 ) ; } void loop ( ) { // Get key value if pressed char customKey = customKeypad . getKey ( ) ; if ( customKey ) { // Print key value to serial monitor Serial . println ( customKey ) ; } } |
The code for this sketch is very simple. The main thing to note is how the keypad library requires its input parameters in an array format.
After including the Keypad library we define a couple of constants for the number of rows and columns in our keypad. If you are using a different keypad then modify these parameters accordingly.
Next, we create an array that represents the rows and columns of the keypad. The elements of the array define the values of each key.
Finally, we define a couple more arrays. These arrays specify the Arduino connections to the row and column pins on the keypad.
We use all of the above arrays with the Keypad library to create an object that represents our keypad.
In the Setup, we just need to start the serial monitor.
The Loop is very simple. We use the getKey method of the keypad library to get a key value when it detects a keypress. Then we simply print that to the serial monitor.
Load the sketch and open your serial monitor, making sure to observe the baud rate (it should be 9600 baud). Now press some keys on the keypad. You should observe the key values displayed on the serial monitor.
Keypad with LCD
Our next experiment is just an extension of the first one. This time we will use an LCD display instead of the serial monitor to read keypress values.
Using a display such as an LCD or OLED display with the keypad is a very common application, as it can give you feedback when you are entering data.
LCD Hookup
To reduce the number of connections required we will be using an LCD display with an I2C backpack. This makes the hookup extremely simple, as illustrated below:
Once you have it all connected we can modify our sketch to use the LCD.
LCD Sketch
Once again we will be making use of a library to simplify our coding. Unlike the previous library, however, this one is not available in the Library Manager.
The LiquidCrystal_I2C Library is specifically meant for driving LCD displays that use the I2C backpack. You can download this from GitHub as a ZIP file.
Once you have the ZIP file downloaded you'll need to install the library.
- Open the Arduino IDE.
- Select Sketch from the top menu
- Scroll down and highlight Include Library . A sub-menu will open.
- Select Add ZIP Library. This will open a file dialog box.
- Use the dialog box to navigate to the ZIP file you downloaded and select it.
- Click OK to install the library.
Now that you have the library let's take a look at our modified sketch.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | /* Matrix Keypad with LCD Display Demo keypad-demo-lcd.ino Demonstrates use of 4x4 matrix membrane keypad with Arduino Results on LCD Display Display uses I2C backpack DroneBot Workshop 2020 https://dronebotworkshop.com */ // Include Arduino Wire library for I2C #include <Wire.h> // Include LCD display library for I2C #include <LiquidCrystal_I2C.h> // Include Keypad library #include <Keypad.h> // Constants for row and column sizes const byte ROWS = 4 ; const byte COLS = 4 ; // Array to represent keys on keypad char hexaKeys [ ROWS ] [ COLS ] = { { '1' , '2' , '3' , 'A' } , { '4' , '5' , '6' , 'B' } , { '7' , '8' , '9' , 'C' } , { '*' , '0' , '#' , 'D' } } ; // Connections to Arduino byte rowPins [ ROWS ] = { 9 , 8 , 7 , 6 } ; byte colPins [ COLS ] = { 5 , 4 , 3 , 2 } ; // Create keypad object Keypad customKeypad = Keypad ( makeKeymap ( hexaKeys ) , rowPins , colPins , ROWS , COLS ) ; // Create LCD object LiquidCrystal_I2C lcd ( 0x3F , 16 , 2 ) ; void setup ( ) { // Setup LCD with backlight and initialize lcd . backlight ( ) ; lcd . init ( ) ; } void loop ( ) { // Get key value if pressed char customKey = customKeypad . getKey ( ) ; if ( customKey ) { // Clear LCD display and print character lcd . clear ( ) ; lcd . setCursor ( 0 , 0 ) ; lcd . print ( customKey ) ; } } |
A quick look at the code confirms what you probably already suspected – this sketch is virtually identical to the last sketch!
One difference, of course, is that we are including both the Wire Library for I2C and the new LiquidCrystal_I2C library that we just installed. Both of these libraries are required to use the LCD display with the I2C backpack.
In line 39 we create an object to represent our LCD display. The first parameter in the object is "0x3F", which is the hexadecimal I2C address of the display. If you are using a display that has a different I2C address you will need to modify this parameter accordingly.
In the Setup we initialize the LCD display and also enable its backlight.
The Loop is almost identical to the previous sketch. Once again we get the value of the keypress and hold it in a character variable. Then we clear the LCD display and print the character to the display. It will remain on the display until the next key is pressed.
Load the sketch and observe the display while you press keys. If you don't see anything try adjusting the brightness control on the I2C backpack.
Now that we have the basics down let's build something practical with our keypad.
Combination Lock
A great use for a matrix keypad is to build a combination lock. You can use this to lock a door or a drawer or to regulate access to an electronic device.
Our lock project will drive a relay, which in turn could be used to activate a standard locking solenoid. These devices stay in the locked position and will only release the lock when voltage is applied to them. Typically these devices use 12-volts to operate.
In most cases you'll only want to apply voltage for a few seconds, just enough time to unlock the solenoid to open the guarded area. Applying voltage to the solenoid for too long a period can burn it out, you should read the specifications on your locking mechanism for more details.
Our lock will operate as follows:
- The LCD display will prompt the user to enter a password
- As the password is entered it will be printed on the display
- When the correct number of characters have been entered the code will check the data against the stored combination.
- If the code is correct it will activate the relay for five seconds.
- If the code is incorrect it will display an error message.
- It will then clear the display.
Let's get working on it!
Combination Lock Hookup
All that we need to do to create our lock is to add a relay module to the existing LCD hookup, as shown here.
Relay modules typically have three input connections:
- Ground
- Power (typically 5-volts)
- Trigger or Input
The output of the relay is labeled as follows:
- NC (normally closed)
- Common
- NO (normally open)
Typically you would connect one side of your solenoid (or other activated device) to one side of the power supply (i.e. 12-volts). The other side would be routed between the Common and NO connections of the relay. This way the relay will switch the solenoid on when it is activated.
In my experiment I just used a lamp, as it was easier to see in the video!
After wiring it up it's time to turn our attention to the sketch that will run our combination lock.
Combination Lock Sketch
Here is the code for our combination lock:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | /* Matrix Keypad Combination Lock Demo keypad-demo-lock.ino Combination lock using 4x4 matrix membrane keypad with Arduino Results on LCD display Drives relay DroneBot Workshop 2020 https://dronebotworkshop.com Based upon code from https://www.circuitbasics.com/ */ // Include Arduino Wire library for I2C #include <Wire.h> // Include LCD display library for I2C #include <LiquidCrystal_I2C.h> // Include Keypad library #include <Keypad.h> // Length of password + 1 for null character #define Password_Length 8 // Character to hold password input char Data [ Password_Length ] ; // Password char Master [ Password_Length ] = "123A456" ; // Pin connected to lock relay input int lockOutput = 13 ; // Counter for character entries byte data_count = 0 ; // Character to hold key input char customKey ; // Constants for row and column sizes const byte ROWS = 4 ; const byte COLS = 4 ; // Array to represent keys on keypad char hexaKeys [ ROWS ] [ COLS ] = { { '1' , '2' , '3' , 'A' } , { '4' , '5' , '6' , 'B' } , { '7' , '8' , '9' , 'C' } , { '*' , '0' , '#' , 'D' } } ; // Connections to Arduino byte rowPins [ ROWS ] = { 9 , 8 , 7 , 6 } ; byte colPins [ COLS ] = { 5 , 4 , 3 , 2 } ; // Create keypad object Keypad customKeypad = Keypad ( makeKeymap ( hexaKeys ) , rowPins , colPins , ROWS , COLS ) ; // Create LCD object LiquidCrystal_I2C lcd ( 0x3F , 16 , 2 ) ; void setup ( ) { // Setup LCD with backlight and initialize lcd . backlight ( ) ; lcd . init ( ) ; // Set lockOutput as an OUTPUT pin pinMode ( lockOutput , OUTPUT ) ; } void loop ( ) { // Initialize LCD and print lcd . setCursor ( 0 , 0 ) ; lcd . print ( "Enter Password:" ) ; // Look for keypress customKey = customKeypad . getKey ( ) ; if ( customKey ) { // Enter keypress into array and increment counter Data [ data_count ] = customKey ; lcd . setCursor ( data_count , 1 ) ; lcd . print ( Data [ data_count ] ) ; data_count++; } // See if we have reached the password length if ( data_count == Password_Length - 1 ) { lcd . clear ( ) ; if ( ! strcmp ( Data , Master ) ) { // Password is correct lcd . print ( "Correct" ) ; // Turn on relay for 5 seconds digitalWrite ( lockOutput , HIGH ) ; delay ( 5000 ) ; digitalWrite ( lockOutput , LOW ) ; } else { // Password is incorrect lcd . print ( "Incorrect" ) ; delay ( 1000 ) ; } // Clear data and LCD display lcd . clear ( ) ; clearData ( ) ; } } void clearData ( ) { // Go through array and clear data while ( data_count != 0 ) { Data [ data_count--] = 0 ; } return ; } |
You'll note that it uses the same libraries as the LCD sketch, which of course makes perfect sense.
We define the length of the password on line 23. Note that this also includes a null character, so the value here is actually one more than the actual password length. You can change this to make an easier or harder password.
Two character variable arrays are defined. The Data array holds the key entries, and the Master arry has the actual password. You should edit the password to be something harder to guess than just the first seven digits on the keypad!
We also define the lock output pin. I used pin 13, as the Arduino has a built-in LED on that pin, so it can be used for troubleshooting if the relay fails to activate.
The byte_coun t variable counts the number of keypresses entered.
In the Setup we define pin 13 as an OUTPUT.
We start the Loop by placing the LCD cursor in the top left corner and printing "Enter Password:". Then we look for a keypress, as we did in the previous sketches.
If we get a keypress we record the value in an element of the Data array. We then increment the counter for the next keypress.
After that we check to see if we have enough characters. If we don't we end the Loop and repeat until we do.
Once we have enough characters we compare the Data array to the Master array. If the arrays are identical then we have the correct password and we activate the relay for 5 seconds. If it is incorrect we print "Incorrect" on the display and hold it there for a second.
In both cases we then clear the display and call the clearData function to clean out the Data array.
Load the sketch and give it a try. If you're successful you should now have a working combination lock. You can experiment changing the password length if you wish.
Conclusion
Matrix keypads are an easy-to-use input device that can add a lot of functionality to your Arduino projects. They are inexpensive and they can give your project a professional look and feel.
One of these keypads would be a great addition to your next Arduino project.
Summary
Article Name
Using Keypads with Arduino
Description
Matrix Keypads are easy-to-use input devices that can add a lot of functionality to your Arduino project. In this article, I'll show you how to use these keypads with an Arduino. We will also build an electronic combination lock.
Author
DroneBot Workshop
Publisher Name
DroneBot Workshop
Publisher Logo
mclaughlinruen1959.blogspot.com
Source: https://dronebotworkshop.com/keypads-arduino/
0 Response to "How to Use Keypad Arduino Easy With Servomotor"
Post a Comment