Skip to content

Button

Overview

The Button sample demonstrates the use of GPIO input using the digitalio module. It prints a message to the console each time the state of the button changes.

The table below shows the available button on the nRF52840 Connect Kit:

Button Alias
USER Button USER

Requirements

Before you start, check that you have the required hardware and software:

Running the code

To run the code, complete the following steps:

  1. Connect nRF52840 Connect Kit to your computer using the USB-C Cable.
  2. Start Mu Editor, click Load to open code.py in the CIRCUITPY drive.
  3. Copy and paste the following code into code.py and click Save:

    CIRCUITPY/code.py
    import board
    import digitalio
    
    # User Button
    button = digitalio.DigitalInOut(board.USER)
    button.direction = digitalio.Direction.INPUT
    button.pull = digitalio.Pull.UP
    
    last_value = button.value
    
    while True:
        if last_value != button.value:
            last_value = button.value
            print('Button is ' + ('released' if button.value else 'pressed'))
    
  4. Your code will run as soon as the file is done saving. Click Serial on Mu Editor's Top Menu to open a serial console. Observe the output of the console and press the USER button. You should see the output, similar to what is shown in the following:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    Code stopped by auto-reload. Reloading soon.
    
    Auto-reload is on. Simply save files over USB to run them or enter REPL to disable.
    code.py output:
    Button is pressed
    Button is released
    Button is pressed
    Button is released
    ...