Pyboard's On-board Peripherals - User Switch

Contents

Introduction to Pyboard's User Switch

The Pyboard has an onboard user switch; labelled USR   on the board. It is a push-button momentary (non-latching) switch i.e. the contacts remain closed only while the button is physically held down.

On the board pin X17 is pulled to GND through a 4.7 kΩ resistor. This pin was connected to an Oscilloscope and a scan of a manual push/release cycle of the switch was recorded.

Oscilloscope scan of USR switch push & release.
Fig 1 - Oscilloscope scan of USR switch push & release

Switch bounce appears to be fairly minimal.

MicroPython pyb.Switch Class

A MicroPython program gains access to the switch from the pyb.Switch class. This class is simple and easy to use.


Syntax:
pyb.Switch()
Creates and returns a Switch object.

Syntax:
Switch.value()
Returns True if the switch is pressed down
otherwise False is returned.

Syntax:
Switch.callback(fun)
Register the given function to be called when
the switch is pressed down. If fun is None,
then it disables the callback.

Example:
from pyb import Switch, delay

# Get a Switch object.
switch = Switch()
count = 0

# Monitor the switch for a press.
while True:
  if switch.value():
    count += 1
    print('Switch presses:', count)
  # Pause a little so that multiple instances
  # of the same button push won't be recorded.  
  delay(150)

Typical Output:
Switch presses: 1
Switch presses: 2
Switch presses: 3
Switch presses: 4
Traceback (most recent call last):
  File "<stdin>", line 14, in <module>
KeyboardInterrupt:
          

Example: Using Pyboard's Switch

This example demonstrates the use of a callback function which is called each time the user switch is pressed.

The callback function checks that more than 150 ms has elapsed since last called. This ensures that the same switch press doesn't generate multiple interrupts. The function toggles the orange and blue LEDs on the Pyboard. Initially the orange LED is on and the blue LED is off.

If a KeyboardInterrupt  exception is raised by user interaction (CTRL-C) then it is trapped. Both LEDs are turned off and the program exits safely with a soft reboot.


Example:
# A callback function is attached to the user switch.
# Each time the switch is pressed the orange and blue
# LEDs are toggled.

from pyb import Switch, LED, delay
from time import ticks_ms, ticks_diff
import sys

# Callback function triggered when
# the user switch is pressed.
def toggleLEDs():
    # Can't allocate so must use global variable.
    global tNow, tLast, tDiff
    # Only toggle LEDs if more than 150 ms has
    # elapsed since this function was last called.
    tNow = ticks_ms()
    tDiff = ticks_diff(tNow, tLast)
    if tDiff > 150:
        tLast = tNow
        LedOrange.toggle()
        LedBlue.toggle()

# create global variables
switch = Switch()
LedOrange = LED(3)
LedBlue = LED(4)
tNow = tLast = ticks_ms()
tDiff = ticks_diff(tNow, tLast)
 
# Assign callback function which is called
# each time the user switch is pressed.
switch.callback(toggleLEDs)

LedOrange.on()
LedBlue.off()

# Endless loop does nothing.
# LEDs are toggled with the callback function
# each time the user switch is pressed.
while True:
    # Trap any keyboard interrupt exception and
    # clean up before exiting with a soft reset.
    try:
        delay(1000)
    except KeyboardInterrupt:
        print('\nKeyboard Interrupt.\nTurning both LEDs off.')
        LedOrange.off()
        LedBlue.off()
        sys.exit(0)
          

After pressing CTRL-C the REPL will respond with the following:

  • Keyboard Interrupt.
    Turning both LEDs off.
    MPY: sync filesystems
    MPY: soft reboot