Posted by virantha on Sat 30 March 2019

BrickNil - Control LEGO Bluetooth Sensors and Motors with Python

BrickNil [*] provides an easy way to connect to and program LEGO® Bluetooth hubs (including the PoweredUp Passenger Train 60197 and Cargo Train 60198 sets, and the Lego Duplo Steam Train 10874 and Cargo Train 10875 ) using Python on OS X and Linux. This work was inspired by this EuroBricks thread and the NodeJS Powered-Up library. Unlike the official apps available from LEGO, BrickNil allows you to control multiple hubs with a single program, which lets you easily scale to programming large interactive systems.

BrickNil requires modern Python (designed and tested for 3.7) and uses asynchronous event programming built on top of the Curio async library. As an aside, the choice of async library is fairly arbitrary; and enabling another library such as asyncio or Trio should be straightforward.

An example BrickNil program for controlling the Train motor speed is shown below:

from curio import sleep
from bricknil import attach, start
from bricknil.hub import PoweredUpHub
from bricknil.sensor import TrainMotor

@attach(TrainMotor, name='motor')
class Train(PoweredUpHub):

    async def run(self):
        for i in range(2):  # Repeat this control two times
            await self.motor.ramp_speed(80,5000) # Ramp speed to 80 over 5 seconds
            await sleep(6)
            await self.motor.ramp_speed(0,1000)  # Brake to 0 over 1 second
            await sleep(2)

async def system():
    train = Train('My train')

if __name__ == '__main__':
[*]BrickNil's name comes from the word "Nil" (නිල්) in Sinhala which means Blue (as in Bluetooth)


  • Fully supports Python asynchronous keywords and coroutines
    • Allows expressive concurrent programming using async/await syntax
    • The current implementation uses the async library Curio by David Beazley
  • Cross-platform
    • Uses the Adafruit Bluefruit BluetoothLE library for Mac OS X
    • Uses the Bleak Bluetooth library for Linux and Win10; also tested on Raspberry Pi.
  • Supports the following LEGO® Bluetooth components:

Lego components supported
Peripheral Price Sets Support
PoweredUp Hub (88009) $50 60197, 60198, 76112 LED color, Button, Current, Voltage sensor
PoweredUp Train Motor (88011) $14 60197, 60198 Motor
PoweredUp Remote (88010) $23 60197, 60198 Remote buttons
PoweredUp Light (88005) $10 88005 Brightness
Boost Hub (88006) $80 17101 Motors, Tilt, LED, Button, Current, Voltage sensors
Boost Vision Sensor (88007) $14 17101 Color, distance, count
Boost External Motor (88008) $17 17101 Motor speed, position
Duplo Train Base   10874, 10875 Motor, speedometer, color, distance, speaker, voltage

More documentation

For more examples and documentation, please see the project website

© Virantha Ekanayake. Built using Pelican. Modified svbhack theme, based on theme by Carey Metcalfe