6. API - pi-top Maker Architecture (PMA) Components

_images/components_spread.jpg _images/Alex.jpg

The Foundation & Expansion Plates and all the parts included in the Foundation & Robotics Kit are known as the pi-top Maker Architecture (PMA).

Each PMA component has a Python class provided for it.

Check out Key Concepts: pi-top Maker Architecture for useful information to get started with using PMA.

6.1. Button

_images/button.jpg

Note

This is a Digital Component which connects to a Digital Port [D0-D7].

from time import sleep

from pitop import Button

button = Button("D5")


def on_button_pressed():
    print("Pressed!")


def on_button_released():
    print("Released!")


button.when_pressed = on_button_pressed
button.when_released = on_button_released

while True:
    if button.is_pressed is True:  # When button is pressed it will return True
        print(button.value)
    sleep(1)
class pitop.pma.Button(*args, **kwargs)[source]

Encapsulates the behaviour of a push-button.

A push-button is a simple switch mechanism for controlling some aspect of a circuit.

Parameters:
  • port_name (str) – The ID for the port to which this component is connected

  • name (str) – Component name, defaults to button. Used to access this component when added to a pitop.Pitop object.

property own_state

Representation of an object state that will be used to determine the current state of an object.

close()[source]

Shut down the device and release all associated resources. This method can be called on an already closed device without raising an exception.

This method is primarily intended for interactive use at the command line. It disables the device and releases its pin(s) for use by another device.

You can attempt to do this simply by deleting an object, but unless you’ve cleaned up all references to the object this may not work (even if you’ve cleaned up all references, there’s still no guarantee the garbage collector will actually delete the object at that point). By contrast, the close method provides a means of ensuring that the object is shut down.

For example, if you have a buzzer connected to port D0, but then wish to attach an LED instead:

>>> from pitop import Buzzer, LED
>>> bz = Buzzer("D0")
>>> bz.on()
>>> bz.off()
>>> bz.close()
>>> led = LED("D0")
>>> led.blink()

Device descendents can also be used as context managers using the with statement. For example:

>>> from pitop import Buzzer, LED
>>> with Buzzer("D0") as bz:
...     bz.on()
...
>>> with LED("D0") as led:
...     led.on()
...
property active_time

The length of time (in seconds) that the device has been active for. When the device is inactive, this is None.

property closed

Returns True if the device is closed (see the close() method). Once a device is closed you can no longer use any other methods or properties to control or query the device.

property config

Returns a dictionary with the set of parameters that can be used to recreate an object.

static ensure_pin_factory()

Ensures that Device.pin_factory is set appropriately.

This is called implicitly upon construction of any device, but there are some circumstances where you may need to call it manually. Specifically, when you wish to retrieve board information without constructing any devices, e.g.:

Device.ensure_pin_factory()
info = Device.pin_factory.board_info

If Device.pin_factory is not None, this function does nothing. Otherwise it will attempt to locate and initialize a default pin factory. This may raise a number of different exceptions including ImportError if no valid pin driver can be imported.

classmethod from_config(config_dict)

Creates an instance of a Recreatable object with parameters in the provided dictionary.

classmethod from_file(path)

Creates an instance of an object using the JSON file from the provided path.

property held_time

The length of time (in seconds) that the device has been held for. This is counted from the first execution of the when_held event rather than when the device activated, in contrast to active_time. If the device is not currently held, this is None.

property hold_repeat

If True, when_held will be executed repeatedly with hold_time seconds between each invocation.

property hold_time

The length of time (in seconds) to wait after the device is activated, until executing the when_held handler. If hold_repeat is True, this is also the length of time between invocations of when_held.

static import_class(module_name, class_name)

Imports a class given a module and a class name.

property inactive_time

The length of time (in seconds) that the device has been inactive for. When the device is active, this is None.

property is_active

Returns True if the device is currently active and False otherwise. This property is usually derived from value. Unlike value, this is always a boolean.

property is_held

When True, the device has been active for at least hold_time seconds.

property is_pressed

Returns True if the device is currently active and False otherwise. This property is usually derived from value. Unlike value, this is always a boolean.

property pin

The Pin that the device is connected to. This will be None if the device has been closed (see the close() method). When dealing with GPIO pins, query pin.number to discover the GPIO pin (in BCM numbering) that the device is connected to.

property pressed_time

The length of time (in seconds) that the device has been active for. When the device is inactive, this is None.

print_config()
print_state()
property pull_up

If True, the device uses a pull-up resistor to set the GPIO pin “high” by default.

save_config(path)

Stores the set of parameters to recreate an object in a JSON file.

property state

Returns a dictionary with the state of the current object and all of its children.

property value

Returns 1 if the button is currently pressed, and 0 if it is not.

property values

An infinite iterator of values read from value.

wait_for_active(timeout=None)

Pause the script until the device is activated, or the timeout is reached.

Parameters:

timeout (float or None) – Number of seconds to wait before proceeding. If this is None (the default), then wait indefinitely until the device is active.

wait_for_inactive(timeout=None)

Pause the script until the device is deactivated, or the timeout is reached.

Parameters:

timeout (float or None) – Number of seconds to wait before proceeding. If this is None (the default), then wait indefinitely until the device is inactive.

wait_for_press(timeout=None)

Pause the script until the device is activated, or the timeout is reached.

Parameters:

timeout (float or None) – Number of seconds to wait before proceeding. If this is None (the default), then wait indefinitely until the device is active.

wait_for_release(timeout=None)

Pause the script until the device is deactivated, or the timeout is reached.

Parameters:

timeout (float or None) – Number of seconds to wait before proceeding. If this is None (the default), then wait indefinitely until the device is inactive.

when_activated

The function to run when the device changes state from inactive to active.

This can be set to a function which accepts no (mandatory) parameters, or a Python function which accepts a single mandatory parameter (with as many optional parameters as you like). If the function accepts a single mandatory parameter, the device that activated it will be passed as that parameter.

Set this property to None (the default) to disable the event.

when_deactivated

The function to run when the device changes state from active to inactive.

This can be set to a function which accepts no (mandatory) parameters, or a Python function which accepts a single mandatory parameter (with as many optional parameters as you like). If the function accepts a single mandatory parameter, the device that deactivated it will be passed as that parameter.

Set this property to None (the default) to disable the event.

when_held

The function to run when the device has remained active for hold_time seconds.

This can be set to a function which accepts no (mandatory) parameters, or a Python function which accepts a single mandatory parameter (with as many optional parameters as you like). If the function accepts a single mandatory parameter, the device that activated will be passed as that parameter.

Set this property to None (the default) to disable the event.

when_pressed

The function to run when the device changes state from inactive to active.

This can be set to a function which accepts no (mandatory) parameters, or a Python function which accepts a single mandatory parameter (with as many optional parameters as you like). If the function accepts a single mandatory parameter, the device that activated it will be passed as that parameter.

Set this property to None (the default) to disable the event.

when_released

The function to run when the device changes state from active to inactive.

This can be set to a function which accepts no (mandatory) parameters, or a Python function which accepts a single mandatory parameter (with as many optional parameters as you like). If the function accepts a single mandatory parameter, the device that deactivated it will be passed as that parameter.

Set this property to None (the default) to disable the event.

6.2. Buzzer

_images/buzzer.jpg

Note

This is a Digital Component which connects to a Digital Port [D0-D7].

from time import sleep

from pitop import Buzzer

buzzer = Buzzer("D0")

buzzer.on()  # Set buzzer sound on
print(buzzer.value)  # Return 1 while the buzzer is on
sleep(2)

buzzer.off()  # Set buzzer sound off
print(buzzer.value)  # Return 0 while the buzzer is off
sleep(2)

buzzer.toggle()  # Swap between on and off states
print(buzzer.value)  # Return the current state of the buzzer

sleep(2)

buzzer.off()
class pitop.pma.Buzzer(*args, **kwargs)[source]

Encapsulates the behaviour of a simple buzzer that can be turned on and off.

Parameters:
  • port_name (str) – The ID for the port to which this component is connected

  • name (str) – Component name, defaults to buzzer. Used to access this component when added to a pitop.Pitop object.

property own_state

Representation of an object state that will be used to determine the current state of an object.

close()[source]

Shut down the device and release all associated resources. This method can be called on an already closed device without raising an exception.

This method is primarily intended for interactive use at the command line. It disables the device and releases its pin(s) for use by another device.

You can attempt to do this simply by deleting an object, but unless you’ve cleaned up all references to the object this may not work (even if you’ve cleaned up all references, there’s still no guarantee the garbage collector will actually delete the object at that point). By contrast, the close method provides a means of ensuring that the object is shut down.

For example, if you have a buzzer connected to port D0, but then wish to attach an LED instead:

>>> from pitop import Buzzer, LED
>>> bz = Buzzer("D0")
>>> bz.on()
>>> bz.off()
>>> bz.close()
>>> led = LED("D0")
>>> led.blink()

Device descendents can also be used as context managers using the with statement. For example:

>>> from pitop import Buzzer, LED
>>> with Buzzer("D0") as bz:
...     bz.on()
...
>>> with LED("D0") as led:
...     led.on()
...
property active_high

When True, the value property is True when the device’s pin is high. When False the value property is True when the device’s pin is low (i.e. the value is inverted).

This property can be set after construction; be warned that changing it will invert value (i.e. changing this property doesn’t change the device’s pin state - it just changes how that state is interpreted).

beep(on_time=1, off_time=1, n=None, background=True)

Make the device turn on and off repeatedly.

Parameters:
  • on_time (float) – Number of seconds on. Defaults to 1 second.

  • off_time (float) – Number of seconds off. Defaults to 1 second.

  • n (int or None) – Number of times to blink; None (the default) means forever.

  • background (bool) – If True (the default), start a background thread to continue blinking and return immediately. If False, only return when the blink is finished (warning: the default value of n will result in this method never returning).

Make the device turn on and off repeatedly.

Parameters:
  • on_time (float) – Number of seconds on. Defaults to 1 second.

  • off_time (float) – Number of seconds off. Defaults to 1 second.

  • n (int or None) – Number of times to blink; None (the default) means forever.

  • background (bool) – If True (the default), start a background thread to continue blinking and return immediately. If False, only return when the blink is finished (warning: the default value of n will result in this method never returning).

property closed

Returns True if the device is closed (see the close() method). Once a device is closed you can no longer use any other methods or properties to control or query the device.

property config

Returns a dictionary with the set of parameters that can be used to recreate an object.

static ensure_pin_factory()

Ensures that Device.pin_factory is set appropriately.

This is called implicitly upon construction of any device, but there are some circumstances where you may need to call it manually. Specifically, when you wish to retrieve board information without constructing any devices, e.g.:

Device.ensure_pin_factory()
info = Device.pin_factory.board_info

If Device.pin_factory is not None, this function does nothing. Otherwise it will attempt to locate and initialize a default pin factory. This may raise a number of different exceptions including ImportError if no valid pin driver can be imported.

classmethod from_config(config_dict)

Creates an instance of a Recreatable object with parameters in the provided dictionary.

classmethod from_file(path)

Creates an instance of an object using the JSON file from the provided path.

static import_class(module_name, class_name)

Imports a class given a module and a class name.

property is_active

Returns True if the device is currently active and False otherwise. This property is usually derived from value. Unlike value, this is always a boolean.

off()

Turns the device off.

on()

Turns the device on.

property pin

The Pin that the device is connected to. This will be None if the device has been closed (see the close() method). When dealing with GPIO pins, query pin.number to discover the GPIO pin (in BCM numbering) that the device is connected to.

print_config()
print_state()
save_config(path)

Stores the set of parameters to recreate an object in a JSON file.

property source

The iterable to use as a source of values for value.

property source_delay

The delay (measured in seconds) in the loop used to read values from source. Defaults to 0.01 seconds which is generally sufficient to keep CPU usage to a minimum while providing adequate responsiveness.

property state

Returns a dictionary with the state of the current object and all of its children.

toggle()

Reverse the state of the device. If it’s on, turn it off; if it’s off, turn it on.

property value

Returns 1 if the device is currently active and 0 otherwise. Setting this property changes the state of the device.

property values

An infinite iterator of values read from value.

6.3. Encoder Motor

Note

This is a Motor Component which connects to a MotorEncoder Port [M0-M3].

from time import sleep

from pitop import BrakingType, EncoderMotor, ForwardDirection

# Setup the motor

motor = EncoderMotor("M0", ForwardDirection.COUNTER_CLOCKWISE)
motor.braking_type = BrakingType.COAST


# Move in both directions

rpm_speed = 100
for _ in range(4):
    motor.set_target_rpm(rpm_speed)
    sleep(2)
    motor.set_target_rpm(-rpm_speed)
    sleep(2)

motor.stop()
class pitop.pma.EncoderMotor(port_name, forward_direction, braking_type=BrakingType.BRAKE, wheel_diameter=0.075, name='encoder_motor')[source]

Represents a pi-top motor encoder component.

Note that pi-top motor encoders use a built-in closed-loop control system, that feeds the readings from an encoder sensor to an PID controller. This controller will actively modify the motor’s current to move at the desired speed or position, even if a load is applied to the shaft.

This internal controller is used when moving the motor through set_target_rpm or set_target_speed methods, while using the set_power method will make the motor work in open-loop, not using the controller.

Note

Note that some methods allow to use distance and speed settings in meters and meters per second. These will only make sense when using a wheel attached to the shaft of the motor.

The conversions between angle, rotations and RPM used by the motor to meters and meters/second are performed considering the wheel_diameter parameter. This parameter defaults to the diameter of the wheel included with MMK. If a wheel of different dimmensions is attached to the motor, you’ll need to measure it’s diameter, in order for these methods to work properly.

Parameters:
  • port_name (str) – The ID for the port to which this component is connected.

  • forward_direction (ForwardDirection) – The type of rotation of the motor shaft that corresponds to forward motion.

  • braking_type (BrakingType) – The braking type of the motor. Defaults to coast.

  • wheel_diameter (int or float) – The diameter of the wheel attached to the motor.

  • name (str) – Component name, defaults to encoder_motor. Used to access this component when added to a pitop.Pitop object.

property own_state

Representation of an object state that will be used to determine the current state of an object.

property forward_direction

Represents the forward direction setting used by the motor.

Setting this property will determine on which direction the motor will turn whenever a movement in a particular direction is requested.

Parameters:

forward_direction (ForwardDirection) – The direction that corresponds to forward motion.

property braking_type

Returns the type of braking used by the motor when it’s stopping after a movement.

Setting this property will change the way the motor stops a movement:

  • BrakingType.COAST will make the motor coast to a halt when stopped.

  • BrakingType.BRAKE will cause the motor to actively brake when stopped.

Parameters:

braking_type (BrakingType) – The braking type of the motor.

set_power(power, direction=Direction.FORWARD)[source]

Turn the motor on at the power level provided, in the range -1.0 to.

+1.0, where:

  • 1.0: motor will turn with full power in the direction provided as argument.

  • 0.0: motor will not move.

  • -1.0: motor will turn with full power in the direction contrary to direction.

Warning

Setting a power value out of range will cause the method to raise an exception.

Parameters:
  • power (int or float) – Motor power, in the range -1.0 to +1.0

  • direction (Direction) – Direction to rotate the motor

power()[source]

Get the current power of the motor.

Returns a value from -1.0 to +1.0, assuming the user is controlling the motor using the set_power method (motor is in control mode 0). If this is not the case, returns None.

set_target_rpm(target_rpm, direction=Direction.FORWARD, total_rotations=0.0)[source]

Run the motor at the specified target_rpm RPM.

If desired, a number of full or partial rotations can also be set through the total_rotations parameter. Once reached, the motor will stop. Setting total_rotations to 0 will set the motor to run indefinitely until stopped.

If the desired RPM setting cannot be achieved, torque_limited will be set to True and the motor will run at the maximum possible RPM it is capable of for the instantaneous torque. This means that if the torque lowers, then the RPM will continue to rise until it meets the desired level.

Care needs to be taken here if you want to drive a vehicle forward in a straight line, as the motors are not guaranteed to spin at the same rate if they are torque-limited.

Warning

Setting a target_rpm higher than the maximum allowed will cause the method to throw an exception. To determine what the maximum possible target RPM for the motor is, use the max_rpm method.

Parameters:
  • target_rpm (int or float) – Desired RPM of output shaft

  • direction (Direction) – Direction to rotate the motor. Defaults to forward.

  • total_rotations (int or float) – Total number of rotations to be execute. Set to 0 to run indefinitely.

target_rpm()[source]

Get the desired RPM of the motor output shaft, assuming the user is controlling the motor using set_target_rpm (motor is in control mode 1).

If this is not the case, returns None.

stop()[source]

Stop the motor in all circumstances.

property current_rpm

Returns the actual RPM currently being achieved at the output shaft, measured by the encoder sensor.

This value might differ from the target RPM set through set_target_rpm.

property rotation_counter

Returns the total or partial number of rotations performed by the motor shaft.

Rotations will increment when moving forward, and decrement when moving backward. This value is a float with many decimal points of accuracy, so can be used to monitor even very small turns of the output shaft.

property torque_limited

Check if the actual motor speed or RPM does not match the target speed or RPM.

Returns a boolean value, True if the motor is torque- limited and False if it is not.

property max_rpm

Returns the approximate maximum RPM capable given the motor and gear ratio.

property wheel_diameter

Represents the diameter of the wheel attached to the motor in meters.

This parameter is important if using library functions to measure speed or distance, as these rely on knowing the diameter of the wheel in order to function correctly. Use one of the predefined pi-top wheel and tyre types, or define your own wheel size.

Note

Note the following diameters:

  • pi-top MMK Standard Wheel: 0.060.0m

  • pi-top MMK Standard Wheel with Rubber Tyre: 0.065m

  • pi-top MMK Standard Wheel with tank track: 0.070m

Parameters:

wheel_diameter (int or float) – Wheel diameter in meters.

property wheel_circumference
set_target_speed(target_speed, direction=Direction.FORWARD, distance=0.0)[source]

Run the wheel at the specified target speed in meters per second.

If desired, a distance to travel can also be specified in meters, after which the motor will stop. Setting distance to 0 will set the motor to run indefinitely until stopped.

Warning

Setting a target_speed higher than the maximum allowed will cause the method to throw an exception. To determine what the maximum possible target speed for the motor is, use the max_speed method.

Note

Note that for this method to move the wheel the expected distance, the correct wheel_diameter value needs to be used.

Parameters:
  • target_speed (int or float) – Desired speed in m/s

  • direction (Direction) – Direction to rotate the motor. Defaults to forward.

  • distance (int or float) – Total distance to travel in m. Set to 0 to run indefinitely.

forward(target_speed, distance=0.0)[source]

Run the wheel forward at the desired speed in meters per second.

This method is a simple interface to move the motor that wraps a call to set_target_speed, specifying the forward direction.

If desired, a distance to travel can also be specified in meters, after which the motor will stop. Setting distance to 0 will set the motor to run indefinitely until stopped.

Note

Note that for this method to move the wheel the expected distance, the correct wheel_circumference value needs to be used.

Parameters:
  • target_speed (int or float) – Desired speed in m/s

  • distance (int or float) – Total distance to travel in m. Set to 0 to run indefinitely.

backward(target_speed, distance=0.0)[source]

Run the wheel backwards at the desired speed in meters per second.

This method is a simple interface to move the wheel that wraps a call to set_target_speed, specifying the back direction.

If desired, a distance to travel can also be specified in meters, after which the motor will stop. Setting distance to 0 will set the motor to run indefinitely until stopped.

Note

Note that for this method to move the wheel the expected distance, the correct wheel_circumference value needs to be used.

Parameters:
  • target_speed (int or float) – Desired speed in m/s

  • distance (int or float) – Total distance to travel in m. Set to 0 to run indefinitely.

property current_speed

Returns the speed currently being achieved by the motor in meters per second.

This value may differ from the target speed set through set_target_speed.

property distance

Returns the distance the wheel has travelled in meters.

This value depends on the correct wheel_circumference value being set.

property max_speed

The approximate maximum speed possible for the wheel attached to the motor shaft, given the motor specs, gear ratio and wheel circumference.

This value depends on the correct wheel_circumference value being set.

6.3.1. Parameters

class pitop.pma.parameters.BrakingType(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Braking types.

COAST = 0
BRAKE = 1
class pitop.pma.parameters.ForwardDirection(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Forward directions.

CLOCKWISE = 1
COUNTER_CLOCKWISE = -1
class pitop.pma.parameters.Direction(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Directions.

FORWARD = 1
BACK = -1

6.4. LED

_images/led_red.jpg

Note

This is a Digital Component which connects to a Digital Port [D0-D7].

from time import sleep

from pitop import LED

led = LED("D2")

led.on()
print(led.is_lit)
sleep(1)

led.off()
print(led.is_lit)
sleep(1)

led.toggle()
print(led.is_lit)
sleep(1)

print(led.value)  # Returns 1 is the led is on or 0 if the led is off
class pitop.pma.LED(*args, **kwargs)[source]

Encapsulates the behaviour of an LED.

An LED (Light Emitting Diode) is a simple light source that can be controlled directly.

Parameters:
  • port_name (str) – The ID for the port to which this component is connected

  • name (str) – Component name, defaults to led. Used to access this component when added to a pitop.Pitop object.

property own_state

Representation of an object state that will be used to determine the current state of an object.

close()[source]

Shut down the device and release all associated resources. This method can be called on an already closed device without raising an exception.

This method is primarily intended for interactive use at the command line. It disables the device and releases its pin(s) for use by another device.

You can attempt to do this simply by deleting an object, but unless you’ve cleaned up all references to the object this may not work (even if you’ve cleaned up all references, there’s still no guarantee the garbage collector will actually delete the object at that point). By contrast, the close method provides a means of ensuring that the object is shut down.

For example, if you have a buzzer connected to port D0, but then wish to attach an LED instead:

>>> from pitop import Buzzer, LED
>>> bz = Buzzer("D0")
>>> bz.on()
>>> bz.off()
>>> bz.close()
>>> led = LED("D0")
>>> led.blink()

Device descendents can also be used as context managers using the with statement. For example:

>>> from pitop import Buzzer, LED
>>> with Buzzer("D0") as bz:
...     bz.on()
...
>>> with LED("D0") as led:
...     led.on()
...
property active_high

When True, the value property is True when the device’s pin is high. When False the value property is True when the device’s pin is low (i.e. the value is inverted).

This property can be set after construction; be warned that changing it will invert value (i.e. changing this property doesn’t change the device’s pin state - it just changes how that state is interpreted).

Make the device turn on and off repeatedly.

Parameters:
  • on_time (float) – Number of seconds on. Defaults to 1 second.

  • off_time (float) – Number of seconds off. Defaults to 1 second.

  • n (int or None) – Number of times to blink; None (the default) means forever.

  • background (bool) – If True (the default), start a background thread to continue blinking and return immediately. If False, only return when the blink is finished (warning: the default value of n will result in this method never returning).

property closed

Returns True if the device is closed (see the close() method). Once a device is closed you can no longer use any other methods or properties to control or query the device.

property config

Returns a dictionary with the set of parameters that can be used to recreate an object.

static ensure_pin_factory()

Ensures that Device.pin_factory is set appropriately.

This is called implicitly upon construction of any device, but there are some circumstances where you may need to call it manually. Specifically, when you wish to retrieve board information without constructing any devices, e.g.:

Device.ensure_pin_factory()
info = Device.pin_factory.board_info

If Device.pin_factory is not None, this function does nothing. Otherwise it will attempt to locate and initialize a default pin factory. This may raise a number of different exceptions including ImportError if no valid pin driver can be imported.

classmethod from_config(config_dict)

Creates an instance of a Recreatable object with parameters in the provided dictionary.

classmethod from_file(path)

Creates an instance of an object using the JSON file from the provided path.

static import_class(module_name, class_name)

Imports a class given a module and a class name.

property is_active

Returns True if the device is currently active and False otherwise. This property is usually derived from value. Unlike value, this is always a boolean.

property is_lit

Returns True if the device is currently active and False otherwise. This property is usually derived from value. Unlike value, this is always a boolean.

off()

Turns the device off.

on()

Turns the device on.

property pin

The Pin that the device is connected to. This will be None if the device has been closed (see the close() method). When dealing with GPIO pins, query pin.number to discover the GPIO pin (in BCM numbering) that the device is connected to.

print_config()
print_state()
save_config(path)

Stores the set of parameters to recreate an object in a JSON file.

property source

The iterable to use as a source of values for value.

property source_delay

The delay (measured in seconds) in the loop used to read values from source. Defaults to 0.01 seconds which is generally sufficient to keep CPU usage to a minimum while providing adequate responsiveness.

property state

Returns a dictionary with the state of the current object and all of its children.

toggle()

Reverse the state of the device. If it’s on, turn it off; if it’s off, turn it on.

property value

Returns 1 if the device is currently active and 0 otherwise. Setting this property changes the state of the device.

property values

An infinite iterator of values read from value.

6.5. Light Sensor

_images/light_sensor.jpg

Note

This is a Analog Component which connects to a Analog Port [A0-A3].

from time import sleep

from pitop import LightSensor

light_sensor = LightSensor("A1")

while True:
    # Returns a value depending on the amount of light
    print(light_sensor.reading)
    sleep(0.1)
class pitop.pma.LightSensor(port_name, pin_number=1, name='light_sensor', number_of_samples=3)[source]

Encapsulates the behaviour of a light sensor module.

A simple analogue photo transistor is used to detect the intensity of the light striking the sensor. The component contains a photoresistor which detects light intensity. The resistance decreases as light intensity increases; thus the brighter the light, the higher the voltage.

Uses an Analog-to-Digital Converter (ADC) to turn the analog reading from the sensor into a digital value.

By default, the sensor uses 3 samples to report a reading, which takes around 0.5s. This can be changed by modifying the parameter number_of_samples in the constructor.

Parameters:
  • port_name (str) – The ID for the port to which this component is connected

  • number_of_samples (str) – Amount of sensor samples used to report a reading. Defaults to 3.

  • name (str) – Component name, defaults to light_sensor. Used to access this component when added to a pitop.Pitop object.

property reading

Take a reading from the sensor.

Returns:

A value representing the amount of light striking the sensor at the current time from 0 to 999.

Return type:

float

property value

Get a simple binary value based on a reading from the device.

Returns:

1 if the sensor is detecting any light, 0 otherwise

Return type:

integer

property own_state

Representation of an object state that will be used to determine the current state of an object.

6.6. Potentiometer

_images/potentiometer.jpg

Note

This is a Analog Component which connects to a Analog Port [A0-A3].

from time import sleep

from pitop import Potentiometer

potentiometer = Potentiometer("A3")

while True:
    # Returns the current position of the Potentiometer
    print(potentiometer.position)
    sleep(0.1)
class pitop.pma.Potentiometer(port_name, pin_number=1, name='potentiometer', number_of_samples=1)[source]

Encapsulates the behaviour of a potentiometer.

A potentiometer is a three-terminal resistor with a sliding or rotating contact that forms an adjustable voltage divider. The component is used for measuring the electric potential (voltage) between the two ‘end’ terminals. If only two of the terminals are used, one end and the wiper, it acts as a variable resistor or rheostat. Potentiometers are commonly used to control electrical devices such as volume controls on audio equipment.

Uses an Analog-to-Digital Converter (ADC) to turn the analog reading from the sensor into a digital value.

Parameters:
  • port_name (str) – The ID for the port to which this component is connected

  • number_of_samples (str) – Amount of sensor samples used to report a position. Defaults to 1.

  • name (str) – Component name, defaults to potentiometer. Used to access this component when added to a pitop.Pitop object.

property own_state

Representation of an object state that will be used to determine the current state of an object.

property position

Get the current reading from the sensor.

Returns:

A value representing the potential difference (voltage) from 0 to 999.

Return type:

float

property value

Get a simple binary value based on a reading from the device.

Returns:

1 if the sensor is detecting a potential difference (voltage), 0 otherwise

Return type:

integer

6.7. Servo Motor

Note

This is a Motor Component which connects to a ServoMotor Port [S0-S3].

from time import sleep

from pitop import ServoMotor, ServoMotorSetting

servo = ServoMotor("S0")

# Scan back and forward across a 180 degree angle range in 30 degree hops using default servo speed
for angle in range(90, -100, -30):
    print("Setting angle to", angle)
    servo.target_angle = angle
    sleep(0.5)

# you can also set angle with a different speed than the default
servo_settings = ServoMotorSetting()
servo_settings.speed = 25

for angle in range(-90, 100, 30):
    print("Setting angle to", angle)
    servo_settings.angle = angle
    servo.setting = servo_settings
    sleep(0.5)

sleep(1)

# Scan back and forward displaying current angle and speed
STOP_ANGLE = 80
TARGET_SPEED = 40

print("Sweeping using speed ", -TARGET_SPEED)
servo.target_speed = -TARGET_SPEED

current_state = servo.setting
current_angle = current_state.angle

# sweep using the already set servo speed
servo.sweep()
while current_angle > -STOP_ANGLE:
    current_state = servo.setting
    current_angle = current_state.angle
    current_speed = current_state.speed
    print(f"current_angle: {current_angle} | current_speed: {current_speed}")
    sleep(0.05)

print("Sweeping using speed ", TARGET_SPEED)

# you can also sweep specifying the speed when calling the sweep method
servo.sweep(speed=TARGET_SPEED)
while current_angle < STOP_ANGLE:
    current_state = servo.setting
    current_angle = current_state.angle
    current_speed = current_state.speed
    print(f"current_angle: {current_angle} | current_speed: {current_speed}")
    sleep(0.05)
class pitop.pma.ServoMotor(port_name, zero_point=0, name='servo')[source]

Represents a pi-top servo motor component.

Note that pi-top servo motors use an open-loop control system. As such, the output of the device (e.g. the angle and speed of the servo horn) cannot be measured directly. This means that you can set a target angle or speed for the servo, but you cannot read the current angle or speed.

Parameters:
  • port_name (str) – The ID for the port to which this component is connected.

  • zero_point (int) – A user-defined offset from ‘true’ zero.

  • name (str) – Component name, defaults to servo. Used to access this component when added to a pitop.Pitop object.

property own_state

Representation of an object state that will be used to determine the current state of an object.

stop()[source]

Stop servo at its current position.

Returns:

None

property zero_point

Represents the servo motor angle that the library treats as ‘zero’. This value can be anywhere in the range of -90 to +90.

For example, if the zero_point were set to be -30, then the valid range of values for setting the angle would be -60 to +120.

Warning

Setting a zero point out of the range of -90 to 90 will cause the method to raise an exception.

property angle_range

Returns a tuple with minimum and maximum possible angles where the servo horn can be moved to.

If zero_point is set to 0 (default), the angle range will be (-90, 90).

property setting

Returns the current state of the servo motor, giving current angle and current speed.

Returns:

:class:’ServoMotorSetting` object that has angle and speed attributes.

property current_angle

Returns the current angle that the servo motor is at.

Note

If you need synchronized angle and speed values, use ServoMotor.state() instead, this will return both current angle and current speed at the same time.

Returns:

float value of the current angle of the servo motor in degrees.

property current_speed

Returns the current speed the servo motor is at.

Note

If you need synchronized angle and speed values, use ServoMotor.state() instead, this will return both current angle and current speed at the same time.

Returns:

float value of the current speed of the servo motor in deg/s.

property smooth_acceleration

Gets whether or not the servo is configured to use a linear acceleration profile to ramp speed at start and end of cycle.

Returns:

boolean value of the acceleration mode

property target_angle

Returns the last target angle that has been set.

Returns:

float value of the target angle of the servo motor in deg.

property target_speed

Returns the last target speed that has been set.

Returns:

float value of the target speed of the servo motor in deg/s.

sweep(speed=None)[source]

Moves the servo horn from the current position to one of the servo motor limits (maximum/minimum possible angle), moving at the specified speed. The speed value must be a number from -100.0 to 100.0 deg/s.

The sweep direction is given by the speed.

Setting a speed value higher than zero will move the horn to the maximum angle (90 degrees by default), while a value less than zero will move it to the minimum angle (-90 degress by default).

Warning

Using a speed out of the valid speed range will cause the method to raise an exception.

Parameters:

speed (int or float) – The target speed at which to move the servo horn, from -100 to 100 deg/s.

6.8. Sound Sensor

_images/sound_sensor.jpg

Note

This is a Analog Component which connects to a Analog Port [A0-A3].

from time import sleep

from pitop import SoundSensor

sound_sensor = SoundSensor("A2")

while True:
    # Returns reading the amount of sound in the room
    print(sound_sensor.reading)
    sleep(0.1)
class pitop.pma.SoundSensor(port_name, pin_number=1, name='sound_sensor', number_of_samples=1)[source]

Encapsulates the behaviour of a sound sensor.

A sound sensor component is typically a simple microphone that detects the vibrations of the air entering the sensor and produces an analog reading based on the amplitude of these vibrations.

Uses an Analog-to-Digital Converter (ADC) to turn the analog reading from the sensor into a digital value.

Parameters:
  • port_name (str) – The ID for the port to which this component is connected

  • number_of_samples (str) – Amount of sensor samples used to report a reading. Defaults to 1.

  • name (str) – Component name, defaults to sound_sensor. Used to access this component when added to a pitop.Pitop object.

property reading

Take a reading from the sensor. Uses a builtin peak detection system to retrieve the sound level.

Returns:

A value representing the volume of sound detected by the sensor at the current time from 0 to 500.

Return type:

float

property value

Get a simple binary value based on a reading from the device.

Returns:

1 if the sensor is detecting any sound, 0 otherwise

Return type:

integer

property own_state

Representation of an object state that will be used to determine the current state of an object.

6.9. Ultrasonic Sensor

_images/ultrasonic_sensor.jpg

Note

This is a Digital Component which connects to a Digital Port [D0-D7].

from time import sleep

from pitop import UltrasonicSensor

distance_sensor = UltrasonicSensor("D3", threshold_distance=0.2)

# Set up functions to print when an object crosses 'threshold_distance'
distance_sensor.when_in_range = lambda: print("in range")
distance_sensor.when_out_of_range = lambda: print("out of range")

while True:
    # Print the distance (in meters) to an object in front of the sensor
    print(distance_sensor.distance)
    sleep(0.1)
class pitop.pma.UltrasonicSensor(port_name, queue_len=5, max_distance=3, threshold_distance=0.3, partial=False, name='ultrasonic')[source]
property own_state

Representation of an object state that will be used to determine the current state of an object.

property max_distance

The maximum distance that the sensor will measure in meters.

This value is specified in the constructor and is used to provide the scaling for the value attribute. When distance is equal to max_distance, value will be 1.

property threshold_distance

The distance, measured in meters, that will trigger the when_in_range and when_out_of_range events when crossed.

This is simply a meter-scaled variant of the usual threshold attribute.

property distance

Returns the current distance measured by the sensor in meters.

Note that this property will have a value between 0 and max_distance.

property value

Returns a value between 0, indicating that something is either touching the sensor or is sufficiently near that the sensor can’t tell the difference, and 1, indicating that something is at or beyond the specified max_distance.

property pin
close()[source]

Shut down the device and release all associated resources. This method can be called on an already closed device without raising an exception.

This method is primarily intended for interactive use at the command line. It disables the device and releases its pin(s) for use by another device.

You can attempt to do this simply by deleting an object, but unless you’ve cleaned up all references to the object this may not work (even if you’ve cleaned up all references, there’s still no guarantee the garbage collector will actually delete the object at that point). By contrast, the close method provides a means of ensuring that the object is shut down.

For example, if you have a buzzer connected to port D0, but then wish to attach an LED instead:

>>> from pitop import Buzzer, LED
>>> bz = Buzzer("D0")
>>> bz.on()
>>> bz.off()
>>> bz.close()
>>> led = LED("D0")
>>> led.blink()

Device descendents can also be used as context managers using the with statement. For example:

>>> from pitop import Buzzer, LED
>>> with Buzzer("D0") as bz:
...     bz.on()
...
>>> with LED("D0") as led:
...     led.on()
...
property in_range
property when_in_range
property when_out_of_range
wait_for_in_range(timeout=None)[source]
wait_for_out_of_range(timeout=None)[source]