If you are new to CircuitPython, we recommend you start with the Welcome to CircuitPython Guide then come back here.

Adafruit recommends installing and using the Mu editor, available for Windows, macOS, and Linux. You can learn about Mu in this guide.

The adafruit_hid Library

Adafruit has developed libraries to easily use CircuitPython devices which have HID capabilities as mouse devices. There are several functions you may wish to use in your programs, this guide will show them with examples.

The adafruit_circuitplayground Library

Adafruit has developed a library to access much of the functionality on the Circuit Playground Express called adafruit_circuitplayground. You can use the library by defining 
from import cpx at the start of your code. The library has functions for all the sensors, buttons, etc. The examples will use cpx.button_a and cpx.button_b to read the pushbuttons.

Performing Mouse Clicks

The following performs a mouse left click when Circuit Playground Express Button A is pressed, a right click when Button B is pressed:

from import cpx
from adafruit_hid.mouse import Mouse

m = Mouse()

while True:
    if cpx.button_a:
        while cpx.button_a:    # Wait for button A to be released

    if cpx.button_b:
        while cpx.button_b:    # Wait for button B to be released

When a button is pressed, the code sends the mouse button press notification. It then waits, doing nothing while the button is still pressed. When the button is not pressed anymore, the code sends a mouse release button call.

Moving the Mouse Cursor

The following uses 4 of the capacitive touch pads on the Circuit Playground Express to signal having the mouse move in the +x, +y, -x, and -y axis. This can be changed to switch activations or other methods such as using the accelerometer chip to move based on tilt of the Circuit Playground circuit board.

from import cpx
from adafruit_hid.mouse import Mouse

m = Mouse()

while True:
    if cpx.touch_A4:
        m.move(-1, 0, 0)
    if cpx.touch_A3:
        m.move(1, 0, 0)
    if cpx.touch_A7:
        m.move(0, -1, 0)
    if cpx.touch_A1:
        m.move(0, 1, 0)


The online documentation for the Adafruit HID library is available at on readthedocs.

Adafruit has another guide that goes over the functionality of the adafruit_circuitplayground (CPX) library functions.

Going Further

The mouse keys and cursor code can be merged to one overall mouse program with buttons and cursor control. 

This type of work is terrific for assistive technologies projects.

You can also make a mouse jiggler program which uses the time library along with the mouse library to move the mouse a little, sleep, then do it again. This may keep a computer awake if it has auto shutdown which you cannot change.

This guide was first published on Aug 01, 2018. It was last updated on Aug 01, 2018. This page (CircuitPython) was last updated on May 22, 2019.