Bonside

GPIO

GPIO (General Purpose Input Output) allows your robot to interact with the physical world. This includes turning on LEDs, reading buttons, measuring voltages, or interfacing with simple electronics.

GPIO Overview

The BrainBox provides 4 GPIO pins that can each be configured independently. Before a pin can be used, its operating mode must be set.

GPIO Modes

ModePythonDescription
Digital Output robot.OUTPUT Write a high or low digital signal
Digital Input robot.INPUT Read a high or low digital signal
Analog Input robot.INPUT_ANALOG Read a voltage level, similar to a voltmeter
Pull-up Input robot.INPUT_PULLUP Digital input with an internal pull-up resistor

All modes can be used on all pins. A pin’s mode only needs to be set once, not every time you read or write to it.

Pin Numbering

GPIO pins are numbered 0 to 3. These numbers are used directly when accessing pins in code.

Python Usage

Writing a digital output on pin 0:

R.gpio[0].mode = robot.OUTPUT
R.gpio[0].digital = True

Reading a digital input on pin 1:

R.gpio[1].mode = robot.INPUT
print(R.gpio[1].digital)

Reading an analog voltage on pin 2:

R.gpio[2].mode = robot.INPUT_ANALOG
print(R.gpio[2].analog)

Using a pull-up input on pin 3:

R.gpio[3].mode = robot.INPUT_PULLUP
print(R.gpio[3].digital)
# True when open, False when connected to ground

Worked Example

This example shows multiple GPIO modes in use. The program reads inputs, toggles an output, and prints values to the console.

import robot
import time

R = robot.Robot()

R.gpio[0].mode = robot.INPUT
R.gpio[1].mode = robot.INPUT_ANALOG
R.gpio[2].mode = robot.OUTPUT
R.gpio[3].mode = robot.INPUT_PULLUP

outputState = False

while True:
    print(R.gpio[0].digital)
    print(R.gpio[1].analog)

    outputState = not outputState
    R.gpio[2].digital = outputState

    print(R.gpio[3].digital)
    time.sleep(2)

Pull-up Resistors

Input pins that are not connected to anything are said to be floating. Floating inputs can randomly read high or low depending on electrical noise.

When a pin is set to robot.INPUT_PULLUP, the BrainBox enables an internal resistor connected to 5V. This means the pin will default to reading high unless it is actively pulled low.

This is especially useful for simple switches. You can connect one side of a switch to the GPIO pin and the other to ground. When the switch is open, the pin reads high; when closed, it reads low.