Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

nxt-rs is a Rust library for controlling LEGO MINDSTORMS NXT bricks from a computer. It talks to the brick’s stock firmware over USB or Bluetooth, using the Direct and System commands LEGO documented in the NXT Bluetooth Developer Kit, so you don’t need to install anything on the brick.

use nxt_rs::prelude::*;

fn main() -> nxt_rs::Result<()> {
    let brick = Brick::usb_first().block()?;
    println!("Hello, {}! Battery: {}", brick.name().block()?, brick.battery().block()?);

    let motor = brick.motor(A)?;
    motor.run(power!(75)).degrees(degrees!(360)).wait().block()?;
    Ok(())
}

What you get

  • Two APIs, one connection. The high-level API gives you motors, sensors, files and messages. The low-level API gives you every protocol command as a typed method. You can mix both freely.
  • Mistakes caught by the compiler.
    • A motor can’t be plugged into a sensor port.
    • Two devices can’t share a port within a group.
    • Motor power can’t be out of range.
    • You can’t wait for a motor that never stops.
    • USB-only commands can’t be sent over Bluetooth.
  • Readings with meaning. A touch sensor returns bool, a light sensor a Percent, the ultrasonic sensor Option<Centimeters>, and the colour sensor a ColorName.
  • Async or not, your choice. Everything is async and works with any runtime. Add .block() to use it from plain synchronous code.
  • Testable without a robot. A built-in simulated brick runs your code in unit tests and CI.
  • USB, Bluetooth and serial, on Linux, macOS and Windows.

How this book is organised

  • Getting Started takes you from cargo new to a moving robot.
  • Concepts explains the ideas the API is built on. Read it once and the rest will feel obvious.
  • Connecting, High-level API and Low-level API cover each part of the library in depth.
  • Guides covers testing, complete example robots and troubleshooting.
  • Reference has tables of features, protocol details, status codes and limits.

The API documentation (cargo doc --open) complements this book with every type and method. Every code example in this book is compiled and run as part of the crate’s test suite, so they stay correct.

Requirements

  • A LEGO MINDSTORMS NXT brick (1.0 or 2.0) with LEGO’s standard firmware (or an NBC/NXC “enhanced” firmware). The NXT 2.0 colour sensor needs firmware 1.28 or newer.
  • Rust 1.85 or newer (edition 2024).