Button Press

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 code.py on your CIRCUITPY drive and then connect to the board using the Bluefruit LE Connect app. Then, connect to the serial console.

from adafruit_ble.uart import UARTServer
from adafruit_bluefruit_connect.packet import Packet
from adafruit_bluefruit_connect.button_packet import ButtonPacket

uart_server = UARTServer()

while True:
    uart_server.start_advertising()
    while not uart_server.connected:
        pass

    # Now we're connected

    while uart_server.connected:
        if uart_server.in_waiting:
            packet = Packet.from_stream(uart_server)
            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 Feb 25, 2019. This page (Button Press) was last updated on Oct 14, 2019.