City Hub

../_images/hub-city.png
city hub
city hubchannel0channels12
class CityHub(broadcast_channel=None, observe_channels=[])

LEGO® City Hub.

Parameters:
  • broadcast_channel – Channel number (0 to 255) used to broadcast data. Choose None when not using broadcasting.

  • observe_channels – A list of channels to listen to when hub.ble.observe() is called. Listening to more channels requires more memory. Default is an empty list (no channels).

Using the hub status light

redcity hublighton
light.on(color)

Turns on the light at the specified color.

Parameters:

color (Color) – Color of the light.

city hublightoff
light.off()

Turns off the light.

Blinks the light at a given color by turning it on and off for given durations.

The light keeps blinking indefinitely while the rest of your program keeps running.

This method provides a simple way to make basic but useful patterns. For more generic and multi-color patterns, use animate() instead.

Parameters:
  • color (Color) – Color of the light.

  • durations (list) – Sequence of time values of the form [on_1, off_1, on_2, off_2, ...].

light.animate(colors, interval)

Animates the light with a sequence of colors, shown one by one for the given interval.

The animation runs in the background while the rest of your program keeps running. When the animation completes, it repeats.

Parameters:
  • colors (list) – Sequence of Color values.

  • interval (Number, ms) – Time between color updates.

Using connectionless Bluetooth messaging

city hub000list withbroadcast
awaitble.broadcast(data)

Starts broadcasting the given data on the broadcast_channel you selected when initializing the hub.

Data may be of type int, float, str, bytes, True, or False. It can also be a list or tuple of these.

Choose None to stop broadcasting. This helps improve performance when you don’t need the broadcast feature, especially when observing at the same time.

The total data size is quite limited (26 bytes). True and False take 1 byte each. float takes 5 bytes. int takes 2 to 5 bytes depending on how big the number is. str and bytes take the number of bytes in the object plus one extra byte.

When multitasking, only one task can broadcast at a time. To broadcast information from multiple tasks (or block stacks), you could use a dedicated separate task that broadcast new values when one or more variables change.

Parameters:

data – The value or values to be broadcast.

city hubobserve0
ble.observe(channel) bool | int | float | str | bytes | tuple | None

Retrieves the last observed data for a given channel.

Receiving data is more reliable when the hub is not connected to a computer or other devices at the same time.

Parameters:

channel (int) – The channel to observe (0 to 255).

Returns:

The received data in the same format as it was sent, or None if no recent data is available.

ble.signal_strength(channel) int: dBm

Gets the average signal strength in dBm for the given channel.

This indicates how near the broadcasting device is. Nearby devices may have a signal strength around -40 dBm, while far away devices might have a signal strength around -70 dBm.

Parameters:

channel (int) – The channel number (0 to 255).

Returns:

The signal strength or -128 if there is no recent observed data.

ble.version() str

Gets the firmware version from the Bluetooth chip.

Using the battery

city hubbatteryvoltage
battery.voltage() int: mV

Gets the voltage of the battery.

Returns:

Battery voltage.

city hubbatterycurrent
battery.current() int: mA

Gets the current supplied by the battery.

Returns:

Battery current.

Button and system control

city hubcenteris pressed
buttons.pressed() Set[Button]

Checks which buttons are currently pressed.

Returns:

Set of pressed buttons.

city hubcenterstop button is
city hubnonestop button is
system.set_stop_button(button)

Sets the button or button combination that stops a running script.

Normally, the center button is used to stop a running script. You can change or disable this behavior in order to use the button for other purposes.

Parameters:

button (Button) – A button such as Button.CENTER, or a tuple of multiple buttons. Choose None to disable the stop button altogether. If you do, you can still turn the hub off by holding the center button for three seconds.

system.storage(offset, write=)
system.storage(offset, read=) bytes

Reads or writes binary data to persistent storage.

This lets you store data that can be used the next time you run the program.

The data will be saved to flash memory when you turn the hub off normally. It will not be saved if the batteries are removed while the hub is still running.

Once saved, the data will remain available even after you remove the batteries.

Parameters:
  • offset (int) – The offset from the start of the user storage memory, in bytes.

  • read (int) – The number of bytes to read. Omit this argument when writing.

  • write (bytes) – The bytes to write. Omit this argument when reading.

Returns:

The bytes read if reading, otherwise None.

Raises:

ValueError – If you try to read or write data outside of the allowed range.

You can store up to 128 bytes of data on this hub. The data is cleared when you update the Pybricks firmware or if you restore the original firmware.

system.reset_storage()

Resets all user settings to default values and erases user programs.

city hubshut down
system.shutdown()

Stops your program and shuts the hub down.

Status light examples

Turning the light on and off

from pybricks.hubs import CityHub
from pybricks.parameters import Color
from pybricks.tools import wait

# Initialize the hub.
hub = CityHub()

# Turn the light on and off 5 times.
for i in range(5):

    hub.light.on(Color.RED)
    wait(1000)

    hub.light.off()
    wait(500)

Changing brightness and using custom colors

from pybricks.hubs import CityHub
from pybricks.parameters import Color
from pybricks.tools import wait

# Initialize the hub.
hub = CityHub()

# Show the color at 30% brightness.
hub.light.on(Color.RED * 0.3)

wait(2000)

# Use your own custom color.
hub.light.on(Color(h=30, s=100, v=50))

wait(2000)

# Go through all the colors.
for hue in range(360):
    hub.light.on(Color(hue))
    wait(10)

Creating light animations

from pybricks.hubs import CityHub
from pybricks.parameters import Color
from pybricks.tools import wait
from umath import sin, pi

# Initialize the hub.
hub = CityHub()

# Make an animation with multiple colors.
hub.light.animate([Color.RED, Color.GREEN, Color.NONE], interval=500)

wait(10000)

# Make the color RED grow faint and bright using a sine pattern.
hub.light.animate([Color.RED * (0.5 * sin(i / 15 * pi) + 0.5) for i in range(30)], 40)

wait(10000)

# Cycle through a rainbow of colors.
hub.light.animate([Color(h=i * 8) for i in range(45)], interval=40)

wait(10000)

Bluetooth examples

Broadcasting data to other hubs

from pybricks.hubs import CityHub
from pybricks.pupdevices import Motor
from pybricks.parameters import Port
from pybricks.tools import wait

# Initialize the hub.
hub = CityHub(broadcast_channel=1)

# Initialize the motors.
left_motor = Motor(Port.A)
right_motor = Motor(Port.B)

while True:
    # Read the motor angles to be sent to the other hub.
    left_angle = left_motor.angle()
    right_angle = right_motor.angle()

    # Set the broadcast data and start broadcasting if not already doing so.
    data = (left_angle, right_angle)
    hub.ble.broadcast(data)

    # Broadcasts are only sent every 100 milliseconds, so there is no reason
    # to call the broadcast() method more often than that.
    wait(100)

Observing data from other hubs

from pybricks.hubs import CityHub
from pybricks.pupdevices import Motor
from pybricks.parameters import Color, Port
from pybricks.tools import wait

# Initialize the hub.
hub = CityHub(observe_channels=[1])

# Initialize the motors.
left_motor = Motor(Port.A)
right_motor = Motor(Port.B)

while True:
    # Receive broadcast from the other hub.

    data = hub.ble.observe(1)

    if data is None:
        # No data has been received in the last 1 second.
        hub.light.on(Color.RED)
    else:
        # Data was received and is less that one second old.
        hub.light.on(Color.GREEN)

        # *data* contains the same values in the same order
        # that were passed to hub.ble.broadcast() on the
        # other hub.
        left_angle, right_angle = data

        # Make the motors on this hub mirror the position of the
        # motors on the other hub.
        left_motor.track_target(left_angle)
        right_motor.track_target(right_angle)

    # Broadcasts are only sent every 100 milliseconds, so there is
    # no reason to call the observe() method more often than that.
    wait(100)

Button and system examples

Using the stop button during your program

from pybricks.hubs import CityHub
from pybricks.parameters import Color, Button
from pybricks.tools import wait, StopWatch

# Initialize the hub.
hub = CityHub()

# Disable the stop button.
hub.system.set_stop_button(None)

# Check the button for 5 seconds.
watch = StopWatch()
while watch.time() < 5000:

    # Set light to green if pressed, else red.
    if hub.buttons.pressed():
        hub.light.on(Color.GREEN)
    else:
        hub.light.on(Color.RED)

# Enable the stop button again.
hub.system.set_stop_button(Button.CENTER)

# Now you can press the stop button as usual.
wait(5000)

Turning the hub off

from pybricks.hubs import CityHub
from pybricks.tools import wait

# Initialize the hub.
hub = CityHub()

# Say goodbye and give some time to send it.
print("Goodbye!")
wait(100)

# Shut the hub down.
hub.system.shutdown()