The Bluefruit LE Connect app has a control pad with 8 buttons: UP, DOWN, LEFT, RIGHT, 1, 2, 3 and 4. This demo will show you how to access those buttons, and use them to print a message to the serial console.

Save the following as on your CIRCUITPY drive and then connect to the board using the Bluefruit LE Connect app. Then, connect to the serial console on your computer.

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

from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from import UARTService

from adafruit_bluefruit_connect.packet import Packet
from adafruit_bluefruit_connect.button_packet import ButtonPacket

ble = BLERadio()
uart = UARTService()
advertisement = ProvideServicesAdvertisement(uart)

while True:
    while not ble.connected:

    # Now we're connected

    while ble.connected:
        if uart.in_waiting:
            packet = Packet.from_stream(uart)
            if isinstance(packet, ButtonPacket):
                if packet.pressed:
                    if packet.button == ButtonPacket.BUTTON_1:
                        # The 1 button was pressed.
                        print("1 button pressed!")
                    elif packet.button == ButtonPacket.UP:
                        # The UP button was pressed.
                        print("UP button pressed!")

    # If we got here, we lost the connection. Go up to the top and start
    # advertising again and waiting for a connection.

Connect to your board using the Bluefruit LE Connect application and navigate to the Control Pad page.

Let's take a look at the code.

First we import the necessary libraries and instantiate the UART server.

Inside the loop, we first begin advertising.

Once connected, the board begins listening for packets. In the event that a button packet is received, it checks to see if the button was pressed. Then it checks to see whether it was button 1 or the UP button, and prints a message to the serial console.

The buttons are available as:

  • 1 = ButtonPacket.BUTTON_1
  • 2 = ButtonPacket.BUTTON_2
  • 3 = ButtonPacket.BUTTON_3
  • 4 = ButtonPacket.BUTTON_4
  • UP = ButtonPacket.DOWN
  • DOWN = ButtonPacket.UP
  • LEFT = ButtonPacket.LEFT
  • RIGHT = ButtonPacket.RIGHT

If the board loses connection, the loop will begin again and the board will resume advertising until a new connection is made.

Now you can press the up button or the 1 button, and see the resulting print statement in the serial console!

That's all there is to reading button presses from the Bluefruit LE Connect app with CircuitPython! Now you can use those buttons do all sorts of things like control a servo, light up an LED, or control your robotic creation. Give it a try!

This guide was first published on Feb 25, 2019. It was last updated on Jun 21, 2024.

This page (Button Press) was last updated on Jun 20, 2024.

Text editor powered by tinymce.