> For the complete documentation index, see [llms.txt](https://docs.launchboard.app/cxd/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.launchboard.app/cxd/internet-of-things-project/references-for-wiring-and-coding/keypad.md).

# Keypad

A [12-button keypad](https://www.sparkfun.com/products/8653) can be used as an input for codes or commands. It has buttons for ten digits (`0`-`9`) and two symbols (`*`,`#`).

![](https://576155698-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LDgX-RdB-DPZBPuXzJ1%2F-LDgX75Qrx69yS4tZ2_Z%2F-LDgXGymIzmxiAZvVPHI%2Fkeypad-annotated.jpg?generation=1527608059356932\&alt=media)

The keypad has 9 pinouts, but only the middle 7 are used. (The outer pinout on each side is **not** used.)

The keypad works by wiring the 12 buttons into 3 columns and 4 rows (thus 7 pinout wires). Pressing a button sends a signal through two wires representing the column and row of the key that was pressed. For example, key “8” is in column 2 and row 3 (which correspond to pinout wires 1 and 6).

![](https://576155698-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LDgX-RdB-DPZBPuXzJ1%2F-LDgX75Qrx69yS4tZ2_Z%2F-LDgXGyoME50f-OpRmeV%2Fkeypad-pinouts.jpg?generation=1527608060501324\&alt=media)

Connect wires to each of the 7 pinouts, and then connect the other ends of the wires into different numbered rows in a breadboard. Then use jumper wires and resistors to connect the rows to the Photon.

| Keypad | Photon Pin                             |
| ------ | -------------------------------------- |
| Wire 1 | D5                                     |
| Wire 2 | D3                                     |
| Wire 3 | D6, plus V-USB (5V) using 10K resistor |
| Wire 4 | D0                                     |
| Wire 5 | D4, plus V-USB (5V) using 10K resistor |
| Wire 6 | D1, plus V-USB (5V) using 10K resistor |
| Wire 7 | D2, plus V-USB (5V) using 10K resistor |

**NOTE:** Keypad wires 3, 5, 6, and 7 each have **two** connections. They each connect to an I/O pin, and they each connect to 5V (V-USB) through a 10K resistor. Look at the example wiring diagram for the [photocell](/cxd/internet-of-things-project/references-for-wiring-and-coding/photocell.md) as a visual reference, since it has similar wiring (except the resistor for the keypad will connect to 5V instead of GND).

**FYI:** Notice that this part does **not** connect to GND, which is unusual.

## Code for Keypad

### #Include Library

A code library for the keypad has to be included in your Photon app:

1. In Particle Build, click on the bookmark icon to open the Libraries sidebar.
2. Type "keypad" into the search field. Select the result called: **KEYPAD\_PARTICLE**
3. Click the button to "Include in Project"
4. Select the name of your Photon app, and then click the "Confirm" button
5. Particle Build will automatically insert an `#include` statement at the top of your app code

```java
// This #include statement was automatically added by the Particle IDE.
#include <Keypad_Particle.h>
```

This code library contains special functions that allow you to interact with the keypad.

### Global Variables

In the global variables, you will need to declare variables that will help set up the keypad buttons for the Keypad library functions. You will also need to declare a Keypad object variable that you will use to run the special functions in the library. The example below declares an object variable called "keypad" (but you could use a different variable name).

```java
// global variables to set up keypad buttons
// must use single quotes for key characters
const byte ROWS = 4;
const byte COLS = 3;
char keys[ROWS][COLS] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'*','0','#'}
};
byte rowPins[ROWS] = { D3, D2, D1, D0 };
byte colPins[COLS] = { D6, D5, D4 };

// create Keypad object variable called "keypad"
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
```

You will probably also want to declare variables for a secret PIN code or commands that can be entered to control the device.

```java
// change to any secret PIN of any length
// must use single quotes for key characters
const int PIN_LENGTH = 4;
char secretPIN[PIN_LENGTH] = {'8','3','2','4'}; 

int correctCount = 0;
boolean correctPIN = false;
```

**NOTE:** Be sure to use single quotes when listing key characters (not double quotes).

### setup( ) function

There isn't any code that you need to include in the `setup()` function for the keypad.

### Read Key Press

You can read a key press by using a `keypad.getKey()` statement that will identify which key is being pressed. (If no key is being pressed, the statement returns a value of false.)

If you want to check for a specific key, you can compare the value of `key` to a specific keypad character.

**RECOMMENDED:** Connect the [speaker](/cxd/internet-of-things-project/references-for-wiring-and-coding/speaker.md) to provide audio feedback whenever any key is pressed. Within the `if (key)` statement, play a brief tone if a key is pressed.

```java
void loop() {
    char key = keypad.getKey();
    if (key) {
        tone(speakerPin, 3000, 25); // play sound as feedback when any key pressed
        if (key == '#') {
            // add code to do something if this key is pressed
        }
        delay(100);
    }
}
```

Notice that `delay(100);` was included at the end of the `if(key)` statement. This is because it takes a person a fraction of a second to physically press and release a key. Including a small delay (0.1 seconds) before checking again for a key press will allow the code to detect each key press as a separate event (otherwise, it might detect it as multiple presses of the same key). You may need to fine-tune the delay value based on user testing, so the delay is not too fast and not too slow.

You can also use a series of if-else statements to compare the key pressed against multiple keys, in order to do something different based on which key is pressed.

```java
void loop() {
    char key = keypad.getKey();
    if (key) {
        tone(speakerPin, 3000, 25); // play sound as feedback when any key pressed
        if (key == '1') {
            // add code to do something if this key is pressed
        } else if (key == '2') {
            // add code to do something else if this key is pressed
        } else if (key == '3') {
            // add code to do something else if this key is pressed
        } else {        
            // optional: add code to do something else if any other key pressed
        }
        delay(100);
    }
}
```

**NOTE:** Be sure to use single quotes when listing key characters (not double quotes).

### Detect If Secret PIN Code Entered

Here is an example of a custom function called `checkPIN()` that will detect whether a secret PIN code has been correctly entered. You will need to add instructions to do something if the secret code is correctly entered.

**RECOMMENDED:** Connect the [speaker](/cxd/internet-of-things-project/references-for-wiring-and-coding/speaker.md) to provide audio feedback whenever any key is pressed. Within the `checkCode()` function, play a brief tone if any key is pressed.

```java
void loop() {
    checkPIN();
    if (correctPIN) {
        // do something if secret PIN code entered correctly
    }
}

// custom function to detect if secret PIN code entered
void checkPIN() {
    char key = keypad.getKey();
    // if key pressed, then check which key
    if (key) {
        tone(speakerPin, 3000, 25); // play sound as feedback when any key pressed
        // if key matches next key in secret PIN, add one to correct count
        if (key == secretPIN[correctCount]) {
            correctCount++; 
        } else {
            // else wrong key was entered (reset correct count)
            correctCount = 0; 
        }
        delay(100);
    }
    // check to see if complete secret PIN entered correctly
    if (correctCount == PIN_LENGTH) {
        correctPIN = true;
    }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.launchboard.app/cxd/internet-of-things-project/references-for-wiring-and-coding/keypad.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
