To use the keypad module, you must be running at least CircuitPython 7.0.0-alpha.4!

Using the keys on the Adafruit MacroPad in CircuitPython is super simple, thanks to the keypad module. This module allows you to print the key number, and read key press and releases. The rotaryio module allows you to read the rotation of the rotary encoder, and digitalio allows you to read the rotary encoder button switch presses. All of these modules are built into CircuitPython, meaning to use them, you do not need to load any separate libraries onto your MacroPad.

However, the following example involves the NeoPixel LEDs, which do require a separate library - Adafruit CircuitPython NeoPixel.

Save the following to your CIRCUITPY drive as code.py.

Click the Download Project Bundle button below to download the necessary libraries and the code.py file in a zip file. Extract the contents of the zip file, find your CircuitPython version, and copy the matching entire lib folder and code.py file to your CIRCUITPY drive.

CIRCUITPY
# SPDX-FileCopyrightText: 2021 Kattni Rembor for Adafruit Industries
#
# SPDX-License-Identifier: MIT

"""Keypad and rotary encoder example for Adafruit MacroPad"""
import board
import digitalio
import rotaryio
import neopixel
import keypad
from rainbowio import colorwheel


key_pins = (board.KEY1, board.KEY2, board.KEY3, board.KEY4, board.KEY5, board.KEY6,
            board.KEY7, board.KEY8, board.KEY9, board.KEY10, board.KEY11, board.KEY12)
keys = keypad.Keys(key_pins, value_when_pressed=False, pull=True)

encoder = rotaryio.IncrementalEncoder(board.ROTA, board.ROTB)
button = digitalio.DigitalInOut(board.BUTTON)
button.switch_to_input(pull=digitalio.Pull.UP)

pixels = neopixel.NeoPixel(board.NEOPIXEL, 12, brightness=0.2)

last_position = None
while True:
    if not button.value:
        pixels.brightness = 1.0
    else:
        pixels.brightness = 0.2

    position = encoder.position
    if last_position is None or position != last_position:
        print("Rotary:", position)
    last_position = position

    color_value = (position * 2) % 255

    event = keys.events.get()
    if event:
        print(event)
        if event.pressed:
            pixels[event.key_number] = colorwheel(color_value)
        else:
            pixels[event.key_number] = 0

Now try pressing any of the keys to see a message printed out. The corresponding NeoPixel will light up. To change the color of the NeoPixel and see a value printed out, rotate the rotary encoder. To temporarily increase the brightness of the NeoPixel, press down on the rotary encoder.

Note that the key numbers start at 0, so the printed key numbers are 0-11. The CircuitPython pin names are KEY1 - KEY12. KEY1 is key number 0, KEY2 is key number 1, etc, through KEY12 being key number 11.

This guide was first published on Jun 30, 2021. It was last updated on Sep 14, 2022.

This page (Keypad) was last updated on May 28, 2023.

Text editor powered by tinymce.