element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products & Partners
    Products & Partners
    • Arduino
    • Avnet & Tria Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • About Us
    About the element14 Community
  • Store
    Store
    • Visit Your Store
    • Choose another store...
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      •  Japan
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      •  Vietnam
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
  • Settings
Raspberry Pi Projects
  • Products & Partners
  • Raspberry Pi
  • Raspberry Pi Projects
  • More
  • Cancel
Raspberry Pi Projects
Blog 74HC595: Build a Keyboard/Keypad/Joypad and more!
  • Blog
  • Documents
  • Events
  • Polls
  • Members
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
Join Raspberry Pi Projects to participate - click to join for free!
  • Share
  • More
  • Cancel
Group Actions
  • Group RSS
  • More
  • Cancel
Engagement
  • Author Author: shabaz
  • Date Created: 19 Oct 2026 7:48 PM Date Created
  • Views 524 views
  • Likes 12 likes
  • Comments 15 comments
  • shift register
  • keyboard
  • rpiintermediate
  • keypad
  • rpibeginner
  • raspberry_pi_projects
  • 74hc595
Related
Recommended

74HC595: Build a Keyboard/Keypad/Joypad and more!

shabaz
shabaz
19 Oct 2026

Table of Contents

  • Introduction
  • 74HC595 Explained
  • Circuit
  • Code
  • LED Bonus
  • Building It

Introduction

A while back, I attached a 4x4 keypad matrix to a microcontroller, and it took up eight GPIO inputs. This time around, I noticed I had a load of buttons from an unused project, and decided to rethink things, and ended up building a little custom keypad for the Pi Pico (it can be done with any microcontroller). This could be useful for robotics, gaming, all sorts of things really.

It was a quick weekend project, and I used the parts I had.

The usual problem to solve, as hinted above, is that many buttons can consume a lot of GPIO! Various solutions exist, and (in my opinion) one of the best approaches is to use a GPIO expander chip, because it also eliminates the need for repeated keyboard scanning. Many GPIO expanders have an interrupt output, so all the microcontroller needs to do is enable a GPIO interrupt and in the event that there’s a button change, simply read in the inputs using I2C or SPI.

In the absence of a GPIO expander, there are a few reduced-GPIO key scanning options, and one method is to use a parallel-input-to-serial-output shift register, and clock in all the inputs.

I didn’t have such a shift register, but I had the complete opposite; a serial-input-to-parallel output shift register. I decided to use that, and learned along the way that it’s actually not a bad solution if scanning is acceptable (but there’s a way to use the same circuit and partially eliminate scanning too, if desired). The '595 is a useful problem-solver.

image

74HC595 Explained

There are three parts to the ‘595. The blue part has three inputs, which are initially set low by the microcontroller. Set pin 10 high to keep the shift register out of reset. The other two inouts are a clock and data pair; set the SER data line, and pulse SRCLK high and low to push the bit into the shift register. On the right side, you could attach another shift register if desired.

image

Once the shift register contains the desired logic levels, the middle portion of the ‘595 can be used, by pulsing RCLK high and low. It will store the data into output registers, and you’ll see that on pins QA to QH, provided pin 13 (output enable) is wired low.

When joining up multiple ‘595s in a chain, usually pins 10, 11 and 12 are all wired together across all chain.

Circuit

The result of the circuit and code is to apply a voltage to each push-switch, one at a time, and let the microcontroller sense when the common wire, SW_DATA, goes high. That will only occur if a user presses a button at the time when a voltage is being applied to the switch, therefore rapid scanning is needed, which is not always a major issue with microcontrollers, but it depends on the project if this is convenient or not.

To perform the scanning, three microcontroller output signals are needed for the shift register, but I used four to simplify the coding a little bit.

A weakness in this circuit is that there is nothing to pull the SW_DATA signal sharply down, so a low-value resistor (such as 2.2k as I’ve used) is needed, otherwise the settling time is quite long. If you see erroneous simultaneous button-presses whenever a button is pressed, then the cause is most likely too high a resistor value there.

image

Code

I wrote a very short Pi Pico demo program, that scans the buttons every 100 msec (in practise you’d want to set it to a faster rate), and displays via USB UART two 8-bit hexadecimal values, indicating button(s) pressed.

The way the code works, is that it sets the SER_DAT line high, and then pulses the shift register clock once, then sets SER_DAT low for the rest of the entire scan. That single high value will pulse its way through the shift register on 15 more clock pulses. After each clock pulse, the R_CLK signal is pulsed too; that registers the shift register value to the outputs, therefore driving just one switch line high. After a very short delay (couple of hundred nsec) the microcontroller reads the common switch line, and then the cycle repeats for the remainder switches.

LED Bonus

One of the key things about parallel-output registers, is that they can be used as outputs : ) I decided to append another 74HC595 (these ICs cost about $0.10) and use it for up to 8 LEDs.

image

The code (viewable/downloadable here) doesn’t change much. After all the keys have been scanned, the desired LED settings are clocked in, and then padded with enough zero bits to push past the first shift registers.

Because all the 595’s are chained and I’d joined all the RCLK signals together, it is not possible to solely do a key scan without affecting the LED outputs. However, in practical terms, it makes no difference, because the key scan happens within microseconds, thus leaving plenty of time until the next key scan, for the LED output registers to hold their desired levels.

Building It

I used PB86 switches that I had purchased a while back, they are really convenient because they fit 0.1” perfboard if a couple of tiny plastic locator pegs are snipped off. The odd button in the photo is there for a purpose (I will use it to map different key layouts, if the user holds down that button and presses another).

image

This project is very easy to build because triple ‘595 boards are available:

image

(Image source: Google Images)

I didn’t have such a board, so took the longer route. The underside is very messy.

image

Anyway, this was just supposed to be a quick experiment, and it seems to work fine. The code is in the simple_keypad project repository, and it uses the Pi Pico C/C++ SDK, but it's so simple, that it would be easy to port to Arduino or other platforms.

Thanks for reading!

  • Sign in to reply
  • shabaz
    shabaz 1 month ago in reply to Jan Cumps

    Very efficient technique! 

    I've just learned that adding the LEDs into the shift registers was extremely useful for unintended reasons; it's a built-in analyzer : ) I can confirm the keyboard scan is happening, and can even put button states (to be displayed on the next tick) onto the LEDs, to see what's happening even before attaching any real debugger.

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • Jan Cumps
    Jan Cumps 1 month ago in reply to shabaz

    > It thinks it is possible to do button debounce

    If you need to keep debounce for each button, there is this scalable approach.

    create an array of uint16_t, with an entry for each button.

    When you notice a button is pressed in the scan loop, shift a 1 bit into LSB side of the entry, if not pressed, a 0.

    If , say, you plan to accept it "debounce passed" if it's been high for 3 consecutive loops, you can do that by && the entry with "0b00000111". If that returns true, you have detected a debounced click.

    You can alter the number of scan loops it has to pass, by changing the amount of LSBs to check for.

    Same mechanism can be used for long presses. Say that you except a long press if a button has been consistently pressed for 12 scan loops. In that case, you can say it is long pressed if entry && 0b0000111111111111 returns true

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • shabaz
    shabaz 1 month ago

    Decided to set AI the task of figuring out the potential state machine for each button.

    It thinks it is possible to do button debounce, and also have an event when the button is held for a while, in a total of 5 states.

    The code (which expects to be run periodically, e.g. on a millisecond tick), provides a keypad_buttons_take_events function, which would indicate the key events like BTN_EVENT_PRESSED, BTN_EVENT_LONGPRESS and BTN_EVENT_RELEASED (and the event only occurs once, i.e. it is indeed an event, not a state value).

    I specifically asked for a debounce algorithm which immediately provides an event and deals with the debounce after the event, since that's the way of having a fast response to user input. I asked for the debounce method to just inhibit further button events on that button in question, for a defined period (20 ticks or so at 1msec tick).

    I've not tried this out yet.

    /*
     * keypad_buttons.c
     *
     * Polling-based, per-button state machine. Call keypad_buttons_update()
     * exactly once every KEYPAD_TASK_TICK_PERIOD milliseconds, after filling
     * btn_arr[] with the latest active-high button bits.
     *
     * Button 0 is bit 0 of btn_arr[0], button 7 is bit 7 of btn_arr[0],
     * button 8 is bit 0 of btn_arr[1], etc.
     *
     * Timing constants are MILLISECONDS, not tick counts.
     * Example: 1000 ms at a 10 ms tick is 100 ticks (not 600 ticks).
     *
     * Debounce policy: the first opposite-level transition is accepted
     * immediately and emits an event; further opposite-level samples are
     * ignored until the lockout expires. There is NO stability validation.
     * A new transition can be accepted on the exact tick the lockout expires.
     *
     * Long press starts at the initially accepted press, not after debounce.
     * Long press fires once, on the first tick at/after the threshold, provided
     * the press has not already been released. A release at the exact threshold
     * takes precedence over a long press.
     *
     * Events are latched until retrieved with keypad_buttons_take_events().
     * Repeated events of the same type before retrieval coalesce into one bit.
     */
    
    #include <stdint.h>
    #include <stddef.h>
    
    #ifndef KEYPAD_BUTTON_COUNT
    #define KEYPAD_BUTTON_COUNT       16u
    #endif
    
    #ifndef KEYPAD_TASK_TICK_PERIOD
    #define KEYPAD_TASK_TICK_PERIOD   1u     /* milliseconds: 1 through 10 */
    #endif
    
    #ifndef BTN_DEBOUNCE_PERIOD
    #define BTN_DEBOUNCE_PERIOD       20u    /* milliseconds */
    #endif
    
    #ifndef BTN_LONGPRESS_PERIOD
    #define BTN_LONGPRESS_PERIOD      1000u  /* milliseconds */
    #endif
    
    #if (KEYPAD_BUTTON_COUNT < 1u)
    #error "KEYPAD_BUTTON_COUNT must be at least 1"
    #endif
    #if (KEYPAD_TASK_TICK_PERIOD < 1u) || (KEYPAD_TASK_TICK_PERIOD > 10u)
    #error "KEYPAD_TASK_TICK_PERIOD must be between 1 and 10 ms"
    #endif
    #if (BTN_DEBOUNCE_PERIOD < KEYPAD_TASK_TICK_PERIOD) || \
        ((BTN_DEBOUNCE_PERIOD % KEYPAD_TASK_TICK_PERIOD) != 0u)
    #error "BTN_DEBOUNCE_PERIOD must be a positive multiple of the tick period"
    #endif
    #if (BTN_LONGPRESS_PERIOD < 1u) || (BTN_LONGPRESS_PERIOD > 5000u)
    #error "BTN_LONGPRESS_PERIOD must be between 1 and 5000 ms"
    #endif
    
    #define KEYPAD_BUTTON_BYTES  ((KEYPAD_BUTTON_COUNT + 7u) / 8u)
    #define BTN_DEBOUNCE_TICKS   (BTN_DEBOUNCE_PERIOD / KEYPAD_TASK_TICK_PERIOD)
    /* Ceiling division: a non-multiple hold period rounds up to a scan tick. */
    #define BTN_LONGPRESS_TICKS  \
        ((BTN_LONGPRESS_PERIOD + KEYPAD_TASK_TICK_PERIOD - 1u) / KEYPAD_TASK_TICK_PERIOD)
    
    typedef enum
    {
        BTN_UNPRESSED,          /* Idle; next logic 1 produces PRESS immediately. */
        BTN_PRESS_DEBOUNCE,     /* PRESS emitted; ignore logic 0 for debounce time. */
        BTN_PRESSED,            /* Press accepted; wait for release or long press. */
        BTN_HELD,               /* Long-press event emitted; wait for release. */
        BTN_RELEASE_DEBOUNCE    /* RELEASE emitted; ignore logic 1 for debounce time. */
    } ButtonState;
    
    typedef enum
    {
        BTN_EVENT_NONE       = 0u,
        BTN_EVENT_PRESSED    = 1u << 0,
        BTN_EVENT_RELEASED   = 1u << 1,
        BTN_EVENT_LONGPRESS = 1u << 2
    } ButtonEvent;
    
    typedef struct
    {
        ButtonState state;
        uint16_t debounce_ticks;   /* Ticks since last accepted edge. */
        uint16_t press_ticks;      /* Ticks since accepted press. */
        uint8_t pending_events;    /* Latched ButtonEvent bits. */
    } ButtonContext;
    
    static ButtonContext buttons[KEYPAD_BUTTON_COUNT];
    
    static void button_accept_press(ButtonContext *button)
    {
        button->state = BTN_PRESS_DEBOUNCE;
        button->debounce_ticks = 0u;
        button->press_ticks = 0u;
        button->pending_events |= BTN_EVENT_PRESSED;
    }
    
    static void button_accept_release(ButtonContext *button)
    {
        button->state = BTN_RELEASE_DEBOUNCE;
        button->debounce_ticks = 0u;
        button->press_ticks = 0u;
        button->pending_events |= BTN_EVENT_RELEASED;
    }
    
    void keypad_buttons_init(void)
    {
        for (size_t i = 0u; i < KEYPAD_BUTTON_COUNT; ++i)
        {
            buttons[i].state = BTN_UNPRESSED;
            buttons[i].debounce_ticks = 0u;
            buttons[i].press_ticks = 0u;
            buttons[i].pending_events = BTN_EVENT_NONE;
        }
    }
    
    /*
     * Call once per tick with the freshly scanned input array.
     * This function does not modify btn_arr[].
     *
     * Timing convention: a transition detected in this call is time zero.
     * A lockout of N ticks expires on the Nth subsequent update call.
     */
    void keypad_buttons_update(const uint8_t btn_arr[KEYPAD_BUTTON_BYTES])
    {
        if (btn_arr == NULL)
            return;
    
        for (size_t i = 0u; i < KEYPAD_BUTTON_COUNT; ++i)
        {
            ButtonContext *button = &buttons[i];
            const uint8_t pressed =
                (uint8_t)((btn_arr[i / 8u] >> (i % 8u)) & 1u);
    
            /* Increment timers only for intervals that began on earlier ticks. */
            if (button->state == BTN_PRESS_DEBOUNCE ||
                button->state == BTN_RELEASE_DEBOUNCE)
            {
                if (button->debounce_ticks < BTN_DEBOUNCE_TICKS)
                    ++button->debounce_ticks;
            }
    
            if (button->state == BTN_PRESS_DEBOUNCE ||
                button->state == BTN_PRESSED)
            {
                if (button->press_ticks < BTN_LONGPRESS_TICKS)
                    ++button->press_ticks;
            }
    
            switch (button->state)
            {
                case BTN_UNPRESSED:
                    if (pressed)
                        button_accept_press(button);
                    break;
    
                case BTN_PRESS_DEBOUNCE:
                    if (button->debounce_ticks >= BTN_DEBOUNCE_TICKS)
                    {
                        /* Lockout expired: inspect this tick's input immediately. */
                        if (!pressed)
                        {
                            button_accept_release(button);
                        }
                        else if (button->press_ticks >= BTN_LONGPRESS_TICKS)
                        {
                            button->state = BTN_HELD;
                            button->pending_events |= BTN_EVENT_LONGPRESS;
                        }
                        else
                        {
                            button->state = BTN_PRESSED;
                        }
                    }
                    break;
    
                case BTN_PRESSED:
                    if (!pressed)
                    {
                        button_accept_release(button);
                    }
                    else if (button->press_ticks >= BTN_LONGPRESS_TICKS)
                    {
                        button->state = BTN_HELD;
                        button->pending_events |= BTN_EVENT_LONGPRESS;
                    }
                    break;
    
                case BTN_HELD:
                    if (!pressed)
                        button_accept_release(button);
                    break;
    
                case BTN_RELEASE_DEBOUNCE:
                    if (button->debounce_ticks >= BTN_DEBOUNCE_TICKS)
                    {
                        /* Lockout expired: a high sample is a new press now. */
                        if (pressed)
                            button_accept_press(button);
                        else
                            button->state = BTN_UNPRESSED;
                    }
                    break;
    
                default:
                    /* Recover safely if the state is corrupted. */
                    button->state = BTN_UNPRESSED;
                    button->debounce_ticks = 0u;
                    button->press_ticks = 0u;
                    break;
            }
        }
    }
    
    /* Returns BTN_UNPRESSED for an out-of-range index. */
    ButtonState keypad_buttons_get_state(size_t button_index)
    {
        if (button_index >= KEYPAD_BUTTON_COUNT)
            return BTN_UNPRESSED;
    
        return buttons[button_index].state;
    }
    
    /* Returns and clears all pending events for one button. */
    uint8_t keypad_buttons_take_events(size_t button_index)
    {
        uint8_t events;
    
        if (button_index >= KEYPAD_BUTTON_COUNT)
            return BTN_EVENT_NONE;
    
        events = buttons[button_index].pending_events;
        buttons[button_index].pending_events = BTN_EVENT_NONE;
        return events;
    }
    
    /* Logical accepted status, including either debounce lockout state. */
    uint8_t keypad_buttons_is_pressed(size_t button_index)
    {
        if (button_index >= KEYPAD_BUTTON_COUNT)
            return 0u;
    
        const ButtonState state = buttons[button_index].state;
        return (uint8_t)(state == BTN_PRESS_DEBOUNCE ||
                         state == BTN_PRESSED || state == BTN_HELD);
    }
    
    /* Example integration (not compiled):
     *
     * uint8_t btn_arr[KEYPAD_BUTTON_BYTES];
     * keypad_buttons_init();
     *
     * // Every KEYPAD_TASK_TICK_PERIOD ms:
     * scan_hardware_into(btn_arr);
     * keypad_buttons_update(btn_arr);
     *
     * for (size_t i = 0; i < KEYPAD_BUTTON_COUNT; ++i) {
     *     uint8_t events = keypad_buttons_take_events(i);
     *     if (events & BTN_EVENT_PRESSED)    { ... }
     *     if (events & BTN_EVENT_LONGPRESS)  { ... }
     *     if (events & BTN_EVENT_RELEASED)   { ... }
     * }
     */
    

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • shabaz
    shabaz 1 month ago in reply to DAB

    Hi DAB,

    Thanks!

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • DAB
    DAB 1 month ago

    Very cool.

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
>
element14 Community

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2026 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube