BrickPython API

This describes the BrickPython API in detail.

Scheduler

class Scheduler.Scheduler(timeMillisBetweenWorkCalls=50)[source]

This manages an arbitrary number of coroutines (implemented as generator functions), supporting invoking each every timeMillisBetweenWorkCalls, and detecting when each has completed.

It supports one special coroutine - the updatorCoroutine, which is invoked before and after all the other ones.

addActionCoroutine(*coroutineList)[source]

Adds one or more new motor control coroutines to be scheduled, answering the last coroutine to be added. Action coroutines are scheduled after Sensor coroutines

addSensorCoroutine(*coroutineList)[source]

Adds one or more new sensor/program coroutines to be scheduled, answering the last one to be added. Sensor coroutines are scheduled before Action coroutines

static currentTimeMillis()[source]

Answers the time in floating point milliseconds since program start.

doWork()[source]

Executes all the coroutines, handling exceptions

lastExceptionCaught = None

The most recent exception raised by a coroutine:

static nullCoroutine()[source]

Null coroutine - runs forever and does nothing

numCoroutines()[source]

Answers the number of active coroutines

static runTillAllComplete(*coroutineList)[source]

Coroutine that executes the given coroutines until all have completed or one throws an exception.

static runTillFirstCompletes(*coroutineList)[source]

Coroutine that executes the given coroutines until the first completes, then stops the others and finishes.

stillRunning(*coroutineList)[source]

Answers whether any of the given coroutines are still executing

stopAllCoroutines()[source]

Terminates all coroutines (except the updater one) - rather drastic!

stopCoroutine(*coroutineList)[source]

Terminates the given one or more coroutines

timeMillisToNextCall()[source]

Wait time before the next doWork call should be called.

static waitFor(function, *args)[source]

Coroutine that waits until the given function (with optional parameters) returns True.

static waitMilliseconds(timeMillis)[source]

Coroutine that waits for timeMillis, then finishes.

static withTimeout(timeoutMillis, *coroutineList)[source]

Coroutine that wraps the given coroutine(s) with a timeout

exception Scheduler.StopCoroutineException[source]

Bases: exceptions.Exception

Exception used to stop a coroutine

BrickPiWrapper

class BrickPiWrapper.BrickPiWrapper(portTypes={})[source]

Bases: Scheduler.Scheduler

This extends the Scheduler with functionality specific to the BrickPi

The constructor takes a map giving the class for the sensor connected to each port: 1 through 5.
E.g. BrickPiWrapper( {‘1’: TouchSensor, ‘2’: UltrasonicSensor } )

Motors and sensors are identified by their port names: motors are A to D; sensors 1 to 5.

motor(which)[source]

Answers the corresponding motor, e.g. motor(‘A’)

sensor(which)[source]

Answers the corresponding sensor, e.g. sensor(‘1’)

TkApplication

class TkApplication.TkApplication(sensorConfiguration={})[source]

Bases: BrickPiWrapper.BrickPiWrapper

Main application class using the Tk toolkit. Implements the regular calls required by the scheduler.

The default implementation creates a simple small window which exits when it receives the ‘Q’ key, but this can be changed by overriding the doInitialization() method.

doInitialization()[source]

Default initialization function with a simple window - override if you want something different

mainloop()[source]

The main loop for the application - call this after initialization. Returns on exit.

onKeyPress(event)[source]

Default key press handling - answers True if it’s handled the key. Override this function to add extra keypress handling.

CommandLineApplication

class CommandLineApplication.CommandLineApplication(sensorConfiguration={})[source]

Bases: BrickPiWrapper.BrickPiWrapper

Main application class for command-line only apps. Doesn’t support user input.

mainloop()[source]

The main loop for the application - call this after initialization. Never returns.

Motor

class Motor.Motor(port, scheduler=None)[source]

An NXT motor connected to a BrickPi port.

A motor is identified by its idChar (‘A’ through ‘D’). It has a current position, relative to the basePosition it has set, and a current speed.

It also defines coroutines to position it using the standard PID servo motor algorithm, and to run at a specific speed.

enable(whether)[source]

Sets whether the motor is enabled

enabled()[source]

Answers true if the motor is enabled

idChar = None

Identifier for the motor

moveTo(*args, **kwargs)[source]

Alternative name for coroutine positionUsingPIDAlgorithm

position()[source]

Answers the current position

positionUsingPIDAlgorithm(target, timeoutMillis=3000)[source]

Coroutine to move the motor to position target, stopping after timeoutMillis if it hasnt reached it yet

positionUsingPIDAlgorithmWithoutTimeout(target)[source]

Coroutine to move the motor to position target, using the PID algorithm with the current PIDSettings

power()[source]

Answers the current power setting

runAtConstantSpeed(targetSpeedInClicksPerSecond)[source]

Coroutine to run the motor at constant speed targetSpeedInClicksPerSecond

setPIDSetting(pidSetting)[source]

Sets the parameters for the PID servo motor algorithm

setPower(p)[source]

Sets the power to be sent to the motor

setSpeed(targetSpeedInClicksPerSecond, timeoutMillis=3000)[source]

Coroutine to run the motor at constant speed targetSpeedInClicksPerSecond for time timeoutMillis

speed()[source]

Answers the current speed calculated from the latest two position readings

stopAndDisable()[source]

Stops and disables the motor

zeroPosition()[source]

Resets the motor base for its position to the current position.

class Motor.PIDSetting(distanceMultiplier=0.9, speedMultiplier=0.23, integratedDistanceMultiplier=0.0025, closeEnoughPosition=4, closeEnoughSpeed=10.0)[source]

Settings for the PID servo algorithm. These may differ between motors. The default values are here.

Distances are in clicks, times in ms, motor power between -255 and +255, the sum of distance is added 20 times/sec. Speeds in clicks per second.

closeEnoughPosition = None

Distance in clicks from the target that we’ll accept as got there.

closeEnoughSpeed = None

Speed that we’ll consider as close enough to zero.

distanceMultiplier = None

Factor for motor power as function of distance - in power units per click distance.

integratedDistanceMultiplier = None

Factor for motor power as a function of the integrated distance - in power units per (click-millisecond)

speedMultiplier = None

Factor for motor power as function of speed - in power units per (click per millisecond)

class Motor.TimePosition(time=0.0, position=0)[source]

Represents a motor position at a specific time. Time in milliseconds, position in clicks.

averageSpeedFrom(other)[source]

Answers the speed in clicks per second coming to this point from other

position = None

Position at that time

time = None

Time created

Sensor

class Sensor.LightSensor(port)[source]

Bases: Sensor.Sensor

Represents my NXT color sensor. The BrickPi_Python COLOR_FULL setting didn’t work for me at all - always has value 1. (though it did light up a red LED on the device).

But in RAW mode the sensor does seem to detect the difference between light and dark backgrounds.

value() is either LIGHT or DARK

DARK = 0

Detected a dark background:

LIGHT = 1

Detected a light background:

class Sensor.Sensor(port, sensorType=0)[source]

Sensor, representing a sensor attached to one of the BrickPi ports. Parameter port may be either a value (BrickPi.PORT_1) or an integer ‘1’-‘5’

There are class attributes with the types defined in the BrickPi module, e.g. Sensor.ULTRASONIC_CONT You can configure the sensor type for each port in the initialization parameters to BrickPiWrapper (and derived classes)

Used both as class in its own right, and as superclass for other sensor types.

callbackFunction = None

Function that gets called with new value as parameter when the value changes - default, none.

cookValue(rawValue)[source]

Answers the value to return for a given input sensor reading

displayValue()[source]

Answers a good representation of the current value for display

idChar = None

Character identifying the sensor: 1 through 5.

rawValue = None

The most recent raw value received from the BrickPi

recentValue = None

The most recent value to return

value()[source]

Answers the latest sensor value received

waitForChange()[source]

Coroutine that completes when the sensor value changes

class Sensor.TouchSensor(port)[source]

Bases: Sensor.Sensor

TouchSensor, representing an NXT touch sensor attached to one of the BrickPi ports. Parameter port may be either a value (BrickPi.PORT_1) or an integer ‘1’-‘5’

value() is True if the button is pressed; False otherwise.

class Sensor.UltrasonicSensor(port)[source]

Bases: Sensor.Sensor

Represents an NXT ultrasonic sensor attached to one of the BrickPi ports. Parameter port may be either a value (BrickPi.PORT_1) or an integer ‘1’-‘5’

value() is distance to the nearest 5 cm, with a maximum of MAX_VALUE

MAX_VALUE = 30

The reading when no object is in sight:

ROUND_TO = 5

Round readings to nearest centimeters.

SMOOTHING_RANGE = 10

How many readings to smooth over.

Table Of Contents

Previous topic

Programming with Coroutines

Next topic

BrickPython Example Programs

This Page