Module Reference¶
All Lizard modules have the following methods in common.
| Methods | Description |
|---|---|
module.mute() |
Turn output off |
module.unmute() |
Turn output on |
module.shadow() |
Send all method calls also to another module |
module.broadcast() |
Regularly send properties to another microcontroller (for internal use) |
Shadows are useful if multiple modules should behave exactly the same, e.g. two actuators that should always move synchronously.
The broadcast method is used internally with port expanders.
A module reserves the pins and peripherals it uses on its microcontroller, i.e. GPIO pins, UART ports, the CAN controller and ADC units, until the core restarts.
I2C modules on the same port share its SDA and SCL pins, which stay reserved for that port.
Creating a module on a reserved pin or peripheral fails with an error that names the owner, e.g. pin 15 is already used by module "led".
In the startup script, such an error stops the script like any other error (see Startup Script).
The console UART with its pins and the pins of the SPI flash are reserved from the start.
Only a serial bus can take over the console UART (see Console as Link).
Core¶
The core module encapsulates various properties and methods that are related to the microcontroller itself. It is automatically created right after the boot sequence.
| Properties | Description | Data type |
|---|---|---|
core.debug |
Whether to output debug information to the command line | bool |
core.millis |
Time since booting the microcontroller (ms) | int |
core.heap |
Free heap memory (bytes) | int |
core.last_message_age |
Time since last input message was received and interpreted (ms) | int |
| Methods | Description | Arguments |
|---|---|---|
core.restart() |
Restart the microcontroller | |
core.version() |
Show project name and version | |
core.info() |
Show project name, project version (and Lizard version if different), compile time and IDF version | |
core.print(...) |
Print arbitrary arguments to the command line | arbitrary |
core.output(format) |
Define the output format | str |
core.startup_checksum() |
Show 16-bit checksum of the startup script (sum of its UTF-8 bytes), or the error of a failed !. |
|
core.get_pin_status(pin) |
Print the status of the chosen pin | int |
core.set_pin_level(pin, value) |
Turns the pin into an output and sets its level | int, int |
core.get_pin_strapping(pin) |
Print value of the pin from the strapping register | int |
core.forget_serial_bus() |
Remove the saved SerialBus configuration from NVS | |
core.set_baudrate(baud) |
Persist UART0 baud rate (applied after restart) | int |
core.pause_broadcasts() |
Pause property broadcasts (all modules) | |
core.resume_broadcasts() |
Resume property broadcasts | |
core.clear_schedule() |
Discard all pending scheduled blocks | |
core.keep_alive() |
Reset last_message_age without producing output |
|
core.telemetry(...) |
Define a telemetry frame of properties and variables | see below |
core.telemetry_info() |
Send the layout lines of all telemetry frames again and ask passed-on bus peers for theirs | |
core.clear_telemetry() |
Clear all telemetry frames |
The output format is a string with multiple space-separated elements of the pattern <module>.<property>[:<precision>] or <variable>[:<precision>].
The precision is an optional integer specifying the number of decimal places for a floating point number.
For example, the format "core.millis input.level motor.position:3" might yield an output like "92456 1 12.789".
An empty format "" stops the core line until a new format is set.
core.get_pin_status(pin) reads the pin's voltage, not the output state directly.
UART baud rate:
The console (UART0) defaults to 115200 baud.
core.set_baudrate(baud) persists a new rate to non-volatile storage; it takes effect on the next restart, so the change is not a breaking one for hosts that are not updated yet.
After core.set_baudrate(921600) followed by core.restart(), reconnect with the host tools at the new rate, e.g. ./monitor.py /dev/ttyUSB0 --baud 921600 (monitor.py, configure.py and otb_update.py all accept --baud, defaulting to 115200).
Supported rates are 115200, 230400, 460800, 921600, 1000000, 1500000, 2000000 and 3000000.
Above 921600, check which rates the host's UART actually produces: a Jetson Orin, for example, produces 1000000, 1500000 and 3000000 exactly, but 2000000 about 2 % too slow.
Some USB-UART bridges stop below 3000000.
The host's UART also has to keep up with the rate: a Jetson whose UART received without DMA lost 5 to 20 % of the core's lines at 1500000 to 3000000 (see discussion #260), while with RX DMA enabled in its device tree it ran clean up to 3000000.
If the host cannot talk to the core at the new rate, erase the chip with ./espresso.py erase and flash it again.
Erasing also clears the startup script and the other settings stored in non-volatile storage, so configure the core again afterwards.
Note that the ROM bootloader and the early boot log always use 115200 regardless of this setting, so pre-application boot output will look garbled at higher rates.
Console load:
Sending a line blocks the main loop until its bytes are on the wire, so at 115200 baud only about 115 bytes fit into one 10 ms cycle.
When printing is what stretches at least half of the cycles well past their 10 ms for three seconds in a row, Lizard warns, e.g. warning: printing stretched the loop to 83 ms, the console baud rate is too low for its output, at most once a minute.
Print less, for example by broadcasting fewer proxies, or raise the baud rate.
On an expander the console is its serial link to the core: the warning arrives there with the expander's name in front, e.g. p: warning: …, and the rate in question is that of the link, not the core's UART0.
Telemetry frames:
core.telemetry(...) sends properties and variables in binary form, as one line per frame next to the text lines on the console.
Layout lines name and type the fields, so a reader needs no configuration.
core.telemetry(imu.yaw, imu.pitch, imu.temp) # frame 1, every step
core.telemetry(wheels.linear_speed, wheels.angular_speed, 20) # frame 2, every 20 ms
Each call defines one frame, or several if its values take more than 180 bytes (see below); frame IDs count up from 1 in the order of definition.
The arguments are properties or variables of type bool, int or float, and a field may appear in several calls, but only once per call.
A field's name, <module>.<property> or the variable's name, has at most 200 characters.
An integer literal as last argument is the interval in milliseconds (0 to 3600000); an int variable or property in that place is a field.
Without an interval or with 0, the frame is sent every step.
Frames go out with the 10 ms steps, so the gaps between them vary, e.g. 10 and 20 ms for an interval of 15 ms, but match the interval on average.
Frames are built at the end of the step, after modules, rules and routines, so all fields of a frame come from the same step.
The values of one frame take at most 180 bytes, e.g. 45 floats.
A call whose values take more is split into several frames, each filled up in the order of the arguments, with its own frame ID and layout.
These frames share their timer and are sent in the same step, only once all of them are announced, so they carry the same millis and a reader can merge them into one step by that time.
Every one of them counts against the limit of 255 frames.
core.clear_telemetry() removes all frames and frees their IDs.
A frame line is ~<base64>@xx: a tilde, the Base64 encoding of the frame body (standard alphabet with = padding) and the usual checksum.
| Bytes | Content |
|---|---|
| 1 | frame ID |
| 1 | layout ID, see below |
| 1 | sequence number per frame ID, modulo 256; a gap means lost frames |
| 4 | time since booting (ms) when the frame was built |
| n | values of the fields |
| 2 | CRC-16/CCITT-FALSE over all preceding bytes |
The sequence number starts at 0 when a frame is defined, also when its ID is reused after core.clear_telemetry().
The float and int fields come first, in the order of the arguments: a float as float32, an int as its low 32 bits, so a value beyond the int32 range wraps around instead of sticking at the limit.
Every reader, the host decoder included, reads them as int32.
Send an age rather than a timestamp: a timestamp in µs like last_heartbeat of a CANopen motor turns negative after 36 minutes, and a host reads the time of the sender from the header anyway.
The bool fields follow as bits in their order, least significant bit first, padded to a full byte.
All multi-byte numbers, including the time and the CRC, are little-endian.
A layout line __LAYOUT__v1 <frame>.<index>/<count> <layout ID> <name>:<type> describes one field: its frame ID, its position from 0, the number of fields in the frame, the layout ID in two hex digits, its name and its type: f for float, i for int or ? for bool.
For example, core.telemetry(motor.position, motor.axis_state, motor.enabled) yields:
__LAYOUT__v1 1.0/3 bf motor.position:f@4a
__LAYOUT__v1 1.1/3 bf motor.axis_state:i@76
__LAYOUT__v1 1.2/3 bf motor.enabled:?@6d
~Ab8HQOIBALbznT8IAAAAAY/t@25
The frame body 01 bf 07 40e20100 b6f39d3f 08000000 01 8fed holds frame ID 1, layout ID bf, sequence number 7, millis 123456, the values 1.234, 8 and true, and the CRC.
The layout ID is the low byte of the CRC-16/CCITT-FALSE over the fields as <name>:<type>, separated by spaces, here motor.position:f motor.axis_state:i motor.enabled:?.
A reader decodes a frame only with layout lines of the same frame ID and layout ID, so a frame ID that core.clear_telemetry() frees and a new frame reuses is not decoded with the old fields.
Different fields get the same layout ID with a chance of 1 in 256.
Layout lines go out when a frame is defined and on core.telemetry_info(), four per step in the order of the frames.
A new frame is sent for the first time once all of its layout lines are out.
Frames that are already running keep coming while core.telemetry_info() repeats their layout lines, except on a serial bus peer, see Serial Bus.
There is no timer for them: a host that connects later or logs for hours calls core.telemetry_info() itself.
On a serial bus peer, frames and layout lines go to the coordinator once it polls the peer, see Serial Bus.
Only the prefix ~ and the word __LAYOUT__ stay the same in future versions of the format; the version is part of each layout line.
On the host, the lizard_host package decodes these lines.
Bluetooth¶
Lizard can receive messages via Bluetooth Low Energy, and also send messages in return to a connected device. Simply create a Bluetooth module with a device name of your choice. Received lines are queued and parsed on the main loop, one step later at most. If the main loop is blocked for long and the queue (32 lines) overflows, further lines are dropped and a warning is printed once the main loop continues. Clients uploading many lines at once should therefore pace their writes or wait for a response.
| Constructor | Description | Arguments |
|---|---|---|
bluetooth = Bluetooth(device_name) |
initialize bluetooth with advertised device_name |
str |
| Properties | Description | Data type |
|---|---|---|
bluetooth.connected |
Whether a device is currently connected | bool |
bluetooth.last_message_age |
Time since the last line was received via Bluetooth (ms) | int |
| Methods | Description | Arguments |
|---|---|---|
bluetooth.send(data) |
send data via notification |
str |
bluetooth.set_pin(pin) |
set 6-digit user PIN (000000-999999) | int |
bluetooth.get_pin() |
print current user PIN or "No user PIN set" | |
bluetooth.reset_pin() |
remove the user PIN | |
bluetooth.deactivate_pin() |
Disables PIN enforcement |
Lizard will offer a service 23014CCC-4677-4864-B4C1-8F772B373FAC and a characteristic 37107598-7030-46D3-B688-E3664C1712F0
that allows writing Lizard statements like on the command line.
On a second characteristic 19f91f52-e3b1-4809-9d71-bc16ecd81069 notifications will be emitted when send(data) is executed.
Access is guarded by a PIN on application level; connections are neither encrypted nor bonded.
When a client enables notifications, Lizard sends AUTH_REQUIRED if a PIN is needed and an empty line otherwise.
A phone bonded under older firmware gets its subscription restored on connection and can miss this greeting; it can write an empty line instead, which Lizard answers with AUTH_REQUIRED if a PIN is needed.
The client then writes AUTH <pin> and receives POST /notification Connected or AUTH_FAIL.
Until then, Lizard answers every other line with AUTH_REQUIRED and does not execute it.
bluetooth.send(data) does not reach the client before it has entered the PIN either.
After three wrong PINs or 30 seconds without a PIN attempt, Lizard closes the connection.
The PIN is the user PIN set with bluetooth.set_pin(pin) or, without one, the PIN configured at build time; Lizard prints it on every connection.
After bluetooth.deactivate_pin(), every client is accepted without a PIN until the next restart.
Note that the PIN is sent unencrypted, so it keeps out accidental connections but not someone listening in.
Unlike core.last_message_age, which any input channel resets, bluetooth.last_message_age only counts lines received via Bluetooth.
Together with connected, it lets rules and the host tell a silent or disconnected app apart from a host that keeps talking on UART0.
Neither property stops anything by itself; use the wheels' drive_command_timeout for that (see Machine Safety).
Serial Bus¶
The serial bus module lets multiple ESP32s share a UART link with a coordinator that polls peers in turn.
| Constructor | Description | Arguments |
|---|---|---|
bus = SerialBus(serial, id) |
Attach to a serial module with local node id |
Serial, int |
| Properties | Description | Data type |
|---|---|---|
bus.offset_<id> |
Estimated clock offset of peer <id> (peer clock minus coordinator clock) in milliseconds, NaN while invalid |
float |
bus.offset_<id>_accuracy |
Error bound of offset_<id> in milliseconds (the true offset lies within offset_<id> ± this value) |
float |
bus.telemetry_errors |
Malformed telemetry frames and layout lines of passed-on or mirrored peers, e.g. with a wrong CRC | int |
bus.telemetry_dropped |
Telemetry frames of any peer dropped for room in the inbound queue, e.g. while layout lines are awaited | int |
bus.ignored_lines |
Received lines that are no bus messages and were not printed, e.g. the boot output of a peer | int |
| Methods | Description | Arguments |
|---|---|---|
bus.send(receiver, fmt, args...) |
Send a printf-formatted line to peer receiver (0-254). Specifiers: %d int, %f number (opt. %.Nf), %s string (bool→true/false) |
int, str, ... |
bus.make_coordinator(peer_ids...) |
Set the list of peer IDs, making this node the coordinator | ints |
bus.enable_time_sync() |
Enable clock offset estimation between coordinator and peers (call on all nodes) | |
bus.pass_telemetry(peer_ids...) |
Pass the telemetry frames of these peers, or of all peers without IDs, on to the console | ints |
bus.flash_peer(id, boot, enable) |
Flash peer id through its boot and enable outputs with this node's firmware (see Flashing a Peer) |
int, 2x Output |
The coordinator prints the lines that reach it from its peers, e.g. Ready. and the output of commands sent with bus.send(), with the coordinator's name for the bus and the peer's ID in front, e.g. bus[2]: Ready. for peer 2 of a bus that the coordinator calls bus.
So two buses of a node, e.g. plexus and p0, keep their peers apart, also when both have a peer 2.
Polling:
The coordinator polls its peers in turn, and a peer answers with the messages it has queued.
A poll that its peer does not answer within 250 ms times out with warning: serial bus <name> poll to <id> timed out.
The warning comes once until the peer answers again, e.g. after its restart, and then the coordinator prints serial bus <name>: peer <id> answers again after <n> timed out polls.
Other Lines:
Lines on the link that are no bus messages are not processed, e.g. the boot output or a panic of a peer, or what a peer prints whose bus has not taken over its console.
A coordinator prints those that are readable text, without their Lizard checksum if they have one.
With a single peer it prints them as lines of that peer, e.g. bus[2]: Guru Meditation Error: ..., and with several peers, any of which may have sent the line, with only its name for the bus in front, e.g. bus: Guru Meditation Error: ....
All others, and all such lines on a peer, are counted in ignored_lines and reported with warning: serial bus <name> ignored <n> lines that are no bus messages, at most once per second.
The ROM bootloader and the boot log of a peer always print at 115200 baud, whatever the rate of the link; on a link with another rate they arrive as an unreadable line, so a restart of the peer is followed by one warning about an ignored line.
Time Synchronization:
Calling bus.enable_time_sync() on the coordinator and all peers enables passive clock offset estimation on top of the regular poll cycle.
The coordinator stamps its local esp_timer clock when it sends a POLL (T1) and when it receives the DONE response (T4), and the peer reports its own receive and send stamps (T2, T3) in the DONE response.
Like NTP, the offset is estimated as ((T2 - T1) + (T3 - T4)) / 2, so the peer's processing time between T2 and T3 cancels out, and the remaining unknown transport delay bounds the error of each sample.
The coordinator publishes the estimate as the property offset_<id> and its bound as offset_<id>_accuracy.
This is intended for timestamping sensor data (e.g. wheel odometry) received from bus peers.
- Applying it: a peer timestamp
t_peerin milliseconds maps to coordinator time ast_peer - offset_<id>; mind the units, since the peer'sesp_timerstamps are in microseconds and the properties in milliseconds. - Sign: the offset is the peer's clock minus the coordinator's, so it is positive while the peer's
esp_timerruns ahead; as both sides count from their own boot, a peer that booted later than the coordinator has a negative offset. - Accuracy: each sample's error bound is half the transport time that is not explained by the known airtime of the two frames; samples within 0.5 ms replace the estimate immediately, otherwise the best sample of every 2 s does, so the estimate keeps following crystal drift even on a busy bus. Systematic asymmetries such as RS485 turnaround are not covered by the bound.
- Validity: the properties are NaN until the first sample arrives and return to NaN whenever the estimate turns invalid, i.e. when the peer's poll times out (e.g. across a peer reboot), or when
make_coordinator()orenable_time_sync()is called again, which restarts all estimates. An expander's broadcast carries NaN as the literalnan, so a proxied offset turns NaN as well; the host firmware has to know that literal. - Scope: the properties exist only on the coordinator, are created once both
make_coordinator()andenable_time_sync()have been called, and stay (as NaN) for IDs dropped from a later list. Referencing them on a peer, before they are created, or for an ID that was never listed is an unknown-property error rather than NaN. Behind an expander, the host learns them with the first broadcast afterenable_time_sync(), so a startup script cannot reference them yet. The two properties per peer also count against the coordinator's 1024-byte broadcast line, which overflows at roughly 16 peers; from then on the coordinator reportsbuffer too smallon every step instead of broadcasting any of its properties. - Convergence: the first sample after enabling or after a timeout locks the estimate, whatever its bound, within two poll rounds; while polling pauses (e.g. during an OTB update), the estimate freezes and drifts with the crystals until polling resumes.
- Compatibility: update the coordinator's firmware first, and treat
__POLL__<digits>and__DONE__<digits>,<digits>,<digits>payloads as reserved for this protocol. A coordinator sends a sequence number in its POLL only to peers that have answered with a stamped DONE, so peers with older firmware keep working (without an estimate) until they are updated.
Telemetry Frames:
A peer that defines telemetry frames with core.telemetry(...) sends them to its own console until a coordinator polls it, and from then on to the coordinator until the peer restarts.
A peer whose console is the bus link holds them back until then (see Console as Link).
With the first poll the peer sends their layout lines again, this time to the coordinator.
While layout lines go to the coordinator, the peer holds back all of its frames.
Then it keeps the newest frame of each ID in a slot and sends the slots with the next poll, so a poll delivers the current values and no backlog, and a frame ID arrives at most once per poll of its peer.
A frame that is replaced before it was sent does not count in the sequence number, so a gap is still a loss.
A peer has eight slots; a frame beyond them is not sent, and the peer warns on its own console and through the coordinator, at most every 10 s.
A call that is split into several frames takes one slot per frame; if the slots run out within a call, only its first frames are sent.
The frames of a split call arrive as one step only while a poll can carry them within their interval; a peer that sends more than the bus carries delivers steps with some of their frames missing, without a gap in the sequence numbers.
The coordinator checks payloads starting with ~ or __LAYOUT__ and never processes them as Lizard code.
bus.pass_telemetry() passes the frames and layout lines of all peers on to the console with the coordinator's name for the bus and the peer's ID in front, here bus[2]:, and bus.pass_telemetry(2) only those of peer 2:
bus = SerialBus(serial, 1)
bus.make_coordinator(2, 3)
bus.pass_telemetry(2)
bus[2]: __LAYOUT__v1 1.0/2 d3 motor.position:f@52
bus[2]: __LAYOUT__v1 1.1/2 d3 motor.enabled:?@76
bus[2]: ~AdMHQOIBALbznT8BIbs=@31
Each call replaces the selection of the previous one; without a call nothing is passed on.
Peers send their frames over the bus whether they are passed on or not.
The coordinator drops the frames of a peer it neither passes on nor mirrors with a BusTelemetry without checking them.
Malformed frames and layout lines of passed-on or mirrored peers, e.g. no valid Base64 or with a wrong CRC, are dropped and counted in telemetry_errors.
- Recovery: when a frame arrives whose layout the coordinator does not have or that does not match the frame, e.g. because
pass_telemetrycame after the peer sent its layout lines or the coordinator booted after the peer, it asks the peer for its layout lines withcore.telemetry_info(), at most every 2 s. Until the first of them arrives, at most for 2 s, it does not pass the peer's frames on and counts them intelemetry_dropped, since printing the frames queued ahead of the layout lines would keep the inbound queue full and drop those. A BusTelemetry of the peer still gets them. Frames from before the request are passed on anyway, so a reader skips frames whose layout it has not seen yet. When the peer reportsReady., the coordinator forgets its layouts; the peer sends them again with the first poll. - Late hosts:
core.telemetry_info()on the coordinator also asks every passed-on peer of itsmake_coordinatorlist for its layout lines, so a host that connects later gets them too. - Queues: a bus keeps the messages of each direction at their length in a queue of 4 KB, and telemetry leaves room for eight of the longest messages free (frames on the coordinator, layout lines on the peer), so commands, their replies and update chunks still get through while frames pile up, e.g. while long prints or the startup block the coordinator.
A message takes its length plus 11 to 14 bytes, and a frame is stored without its bus header and checksum, so the room left to telemetry holds 35 frames of 4 floats or 12 frames of 20 floats.
Lost telemetry recovers by itself: the next frame replaces a lost one, and missing layout lines are requested again.
Frames dropped this way are counted in
telemetry_dropped. - Bus load: a frame of n floats or ints is a line of about 5.3·n + 25 bytes, on the bus as well as on the coordinator's console. A frame of 20 floats takes 132 bytes, i.e. 2.9 ms at 460800 baud; 100 such frames per second would take almost a third of the bus. The most one poll can carry is all eight slots with the largest frame of 45 floats, about 2.1 KB: 46 ms at 460800 baud, but 180 ms at 115200 baud, close to the coordinator's poll timeout of 250 ms. The room left to telemetry in the coordinator's queue holds six of these frames, so its loop has to take them while they arrive.
- Console load: the coordinator prints every frame it passes on, and printing blocks its loop until the line is on the wire (see Console load).
So every passed-on frame adds its line's time to the coordinator's loop: a frame of 45 floats takes 5.8 ms at 460800 baud, and one of them every 10 ms already needs more than half of the loop.
A step handles only the messages that were waiting when it started, so frames that arrive faster than the console prints them slow the loop down instead of stalling it; those that no longer fit into the inbound queue are dropped and counted in
telemetry_dropped. - Compatibility: update the coordinator's firmware first, since an older coordinator tries to run the peer's frames and layout lines as Lizard code.
Payloads starting with
~or__LAYOUT__are reserved for telemetry.
Bus Backup:
When a SerialBus is created, its configuration (pins, baud rate, UART number, node ID) is automatically saved to non-volatile storage.
If multiple SerialBus modules exist, only the first one is backed up.
On boot, if the startup script does not create a SerialBus but a backup config exists,
Lizard removes all existing Serial modules and recreates the SerialBus from the saved config.
This keeps the node reachable over the bus even if a broken script is deployed, avoiding the need for physical USB access.
A bus on the console is restored the same way and takes over the console again (see Console as Link).
To remove the saved configuration, call core.forget_serial_bus().
Console as Link: A node can use its console UART as a bus link, e.g. a port expander that is wired to the core by its console pins:
serial = Serial(3, 1, 115200, 0)
bus = SerialBus(serial, 2)
A serial on UART0 with the console's RX and TX pins (3 and 1 on an ESP32, 44 and 43 on an ESP32-S3) leaves the console alone until a serial bus is created on it.
From then on, only the bus reads and writes UART0, at the serial's baud rate, and the node runs no console lines, only commands from the bus.
Everything the node prints goes to the node that polls it, which prints it as a line of this peer, e.g. bus[2]: ....
That includes replies, warnings and the output of unmuted modules.
Lines printed before the first poll wait in the bus queue; when only the room for eight of the longest messages is free, further lines are dropped and a warning with their number follows.
The node does not print Ready. on its console; the coordinator prints it with the first answer, e.g. bus[2]: Ready..
Telemetry frames and their layout lines wait for the first poll.
While the bus has the console, ESP-IDF log and ROM output is dropped, but a panic still reaches the wire (see Other Lines).
Put the two lines at the top of the startup script, so that the output of the lines below reaches the coordinator, including an error that stops the script.
What the node prints before the bus takes over the console still goes out on the console itself, e.g. an error in a line above the two.
While the bus backup holds a bus on the console pins, i.e. from the boot after the first one with that bus, the console starts at the bus's baud rate instead of its own, so that the coordinator can read these lines and prints them (see Other Lines).
If no bus takes the console over during such a boot, the console returns to its own baud rate before it prints Ready..
A startup script that keeps failing is skipped after two failed boots (see Startup Script); the bus backup then takes over the console again, and the lines the node printed before tell the coordinator why.
The console stays silent on USB as long as the startup script or the bus backup creates the bus, also after ./espresso.py flash, which keeps both.
To get it back, send the node !-, !. and core.forget_serial_bus() over the bus and restart it, or erase its flash with ./espresso.py erase and flash it again; it then runs at its own baud rate again (see core.set_baudrate()).
Flashing a Peer: A coordinator can flash a peer that is wired to it by the bus's RX and TX pins and by two outputs to the peer's GPIO0 and EN, e.g. a port expander:
serial = Serial(26, 27, 460800, 1)
p0 = SerialBus(serial, 1)
p0.make_coordinator(2)
p0_boot = Output(25)
p0_boot.on()
p0_enable = Output(14)
p0_enable.on()
Keep both outputs on while the peer runs, and turn the boot output on first, so that the peer starts its firmware and not its bootloader.
With these lines in the coordinator's startup script, p0.flash_peer(2, p0_boot, p0_enable) flashes the peer, sent once, e.g. from the command line; in the startup script it would flash the peer with every boot.
A port expander on a Robot Brain does not run while its enable pin is not driven high.
flash_peer copies this node's firmware onto the peer like expander.flash() at 921600 baud, whatever the link's rate, which erases the peer's NVS, i.e. its startup script, its bus backup and a persisted console baud rate.
It needs no answer from the peer, so it also flashes a peer without firmware.
It does not check the strapping pins; a peer that does not enter its bootloader fails the transfer before anything is erased.
The copy boots with its console at 115200 baud; the coordinator writes it the two lines of a bus on its console as its startup script, with the baud rate of the coordinator's serial and the ID id, and restarts it (see Console as Link).
The rest of the peer's startup script goes over the bus, e.g. with configure.py --serial-bus 2 --bus-name p0, which replaces the whole script, so keep the two lines at its top.
flash_peer blocks the main loop for the whole transfer like expander.flash().
It fails if another module uses the serial, if boot or enable is no output on a pin of this node, or if the copy does not report Ready. within 5 s.
It drives the two pins itself while flashing; afterwards they are high and follow their outputs again, and a peer that a failed transfer left in its bootloader is restarted through its enable pin.
Firmware Updates:
Peers on the serial bus can be updated remotely via the coordinator.
Use the otb_update.py tool to push new firmware to any peer node.
See OTB Update for details.
Bus Telemetry¶
On a serial bus coordinator, a BusTelemetry module mirrors values that one peer sends in its telemetry frames, so that rules, core.output and the coordinator's own frames can use them.
| Constructor | Description | Arguments |
|---|---|---|
arm = BusTelemetry(bus, peer_id) |
Mirror values of peer peer_id |
SerialBus, int |
The module has no properties of its own. Each value it mirrors is a property declaration with the name the peer gives the field:
bus = SerialBus(serial, 1)
bus.make_coordinator(2)
arm = BusTelemetry(bus, 2)
bool arm.motor.enabled = false # property motor.enabled of peer 2
float arm.motor.position = 0.0
bool arm.parked = false # variable parked of peer 2
when arm.motor.enabled then wheels.locked = true end
core.telemetry(wheels.linear_speed, arm.motor.position, 100)
Peer 2 has to send these values in one of its frames, e.g. with core.telemetry(motor.position, motor.enabled, parked, 100) in its startup.
Two identical peers become two modules, e.g. arm1 = BusTelemetry(bus, 2) and arm2 = BusTelemetry(bus, 3).
- Declarations: only
bool,intandfloatcan be declared. Declaring a name again with the same type only sets the value while no frame has delivered one yet. Another type is an error, and so is the same name of the same peer in a second module, e.g."motor.position" of peer 2 is already declared by arm. - Values: a declared property is read-only.
It keeps its declared value until a frame delivers one, and its last value when the peer stops sending or restarts.
An
intarrives as int32, as at every reader of the frame format, so a value beyond that range wraps around. - Layouts: mirroring works whether or not the coordinator passes the peer's frames on. A declaration made later, e.g. at the console, asks the peer for its layout lines again, so the value follows shortly after; the other mirrored values keep following meanwhile. When the peer gives a frame ID to other fields, the module drops the old mapping, so a property does not take the value of another field, and the check for missing names runs again.
- Warnings: a field the peer sends with another type is not mirrored, and the module warns once, e.g.
warning: arm: peer 2 sends "motor.position" as a boolean, not a number. When the peer's frames arrive but none carries a declared name within 5 s, the module warns once, e.g.warning: arm: no frame of peer 2 carries "parked". Both warnings come once per run of the peer, i.e. again after itsReady.. When no frame of the peer arrives within 5 s of a declaration or of the peer'sReady., e.g. because its startup sends none, the peer ID is wrong or the peer is not polled, the module warns once, e.g.warning: arm: no frame of peer 2 within 5 s. A peer whose layout lines have another version than this node reads is not mirrored; the bus warns once per run of the peer, e.g.warning: serial bus bus does not read layout version 2 of peer 2, only version 1, and the module does not report its names as missing. - Cost: each mirrored value takes about 100 bytes of heap on the coordinator.
Rules over many mirrored values are expensive on their own, so a peer should compute a predicate like
parkeditself and the coordinator mirror one bool.
Input¶
The input module is associated with a digital input pin that is be connected to a pushbutton, sensor or other input signal.
| Constructor | Description | Arguments |
|---|---|---|
input = Input(pin) |
pin is the corresponding GPIO number |
int |
| Properties | Description | Data type |
|---|---|---|
input.level |
Current signal level (0 or 1) | int |
input.change |
Level change since last cycle (-1..1) | int |
input.inverted |
Inverts the active property if true | bool |
input.active |
Current active state of the input | bool |
Usually, an input is considered active if and only if its level is high.
If the inverted property is set to true, the input is considered active if and only if its level is low.
| Methods | Description |
|---|---|
input.get() |
Output the current level |
input.pullup() |
Add an internal pull-up resistor |
input.pulldown() |
Add an internal pull-down resistor |
input.pulloff() |
Remove internal pull resistor |
Output¶
The output module is associated with a digital output pin that is connected to an LED, actuator or other output signal.
| Constructor | Description | Arguments |
|---|---|---|
output = Output(pin) |
pin is the corresponding GPIO number |
int |
| Properties | Description | Data type |
|---|---|---|
output.level |
Current signal level (0 or 1) | int |
output.change |
Level change since last cycle (-1..1) | int |
output.enabled |
Whether the output is enabled | bool |
output.inverted |
Whether the output is inverted | bool |
output.active |
Whether the output is active | bool |
Usually, an output is considered active if and only if its level is high.
If the inverted property is set to true, the output is considered active if and only if its level is low.
| Methods | Description | Arguments |
|---|---|---|
output.on() |
Set the output pin high | |
output.off() |
Set the output pin low | |
output.level(value) |
Set the output level to the given value |
bool |
output.pulse(interval[, duty_cycle]) |
Switch output on and off | floats |
output.enable() |
Enable the output | |
output.disable() |
Disable the output | |
output.activate() |
Activate the output | |
output.deactivate() |
Deactivate the output |
The pulse() method allows pulsing an output with a given interval in seconds and an optional duty cycle between 0 and 1 (0.5 by default).
Note that the pulsing frequency is limited by the main loop to around 20 Hz.
When the output is disabled, it will deactivate and ignore on/off or level commands.
PWM Output¶
The PWM output module is associated with a digital output pin that is connected to an LED, actuator or other output signal.
| Constructor | Description | Arguments |
|---|---|---|
pwm = PwmOutput(pin[, lt[, lc]]) |
pin is the corresponding GPIO number |
1–3x int |
The constructor arguments lt (LEDC timer) and lc (LEDC channel) are optional and default to 0.
When using multiple PWM outputs, set different channel IDs to avoid conflicts.
Channels sharing a timer also share its frequency: a new output adopts the timer's frequency, and setting frequency on one output changes it for all of them.
Use different timers to run outputs at independent frequencies.
The lowest reachable frequency is about 4 Hz on the ESP32 and about 70 Hz on the ESP32-S3; lower values are rejected with an error.
On the ESP32-S3 all timers share one clock source, so the 70 Hz are only reachable while no other timer is in use, also none of a StepperMotor.
With a second timer running, all frequencies must fit the same source, in practice all above about 306 Hz or all on one timer; a value that needs another source is rejected with an error.
| Properties | Description | Data type |
|---|---|---|
pwm.duty |
Duty cycle (0..256, default: 128) | int |
pwm.frequency |
Frequency (Hz, 1..312500, default: 1000) | int |
pwm.enabled |
Whether the output is enabled | bool |
A PWM period is divided into 256 steps, and duty sets for how many of them the pin stays high.
That makes 257 settings, one more than an 8 bit value holds:
duty |
Output |
|---|---|
| 0 | always low |
| 128 | high for half of the period |
| 255 | high for 255 of 256 steps, not fully on |
| 256 | always high |
| Methods | Description | Arguments |
|---|---|---|
pwm.on() |
Turn on the PWM signal | |
pwm.off() |
Turn off the PWM signal | |
pwm.enable() |
Enable the PWM output | |
pwm.disable() |
Disable the PWM output |
When the output is disabled, it will turn off the PWM signal and ignore on/off commands.
MCP23017 Port Expander¶
The MCP23017 allows controlling up to 16 general purpose input or output pins via I2C.
| Constructor | Description | Arguments |
|---|---|---|
mcp = Mcp23017([port[, sda[, scl[, address[, clk_speed]]]]]) |
See below | ints |
The constructor expects up to five arguments:
port: 0 or 1, since the ESP32 has two I2C ports (default: 0)sda: SDA pin (default: 21)scl: SCL pin (default: 22)address: client address of the MCP (0x20..0x28, default: 0x20)clk_speed: I2C clock speed (default: 100000)
| Properties | Description | Data type |
|---|---|---|
mcp.levels |
Levels of all 16 pins | int |
mcp.inputs |
Input mode of all 16 pins | int |
mcp.pullups |
Pull-up resistors for all 16 pins | int |
The properties levels, inputs and pullups contain binary information for all 16 pins in form of a 16 bit unsigned integer.
| Methods | Description | Arguments |
|---|---|---|
mcp.levels(value) |
Set levels of all 16 pins | int |
mcp.inputs(value) |
Set input mode of all 16 pins | int |
mcp.pullups(value) |
Set pull-up resistors for all 16 pins | int |
The methods levels(), inputs() and pullups() expect a 16 bit unsigned integer value containing binary information for all 16 pins.
Use inputs() to configure input and output pins, e.g. inputs(0xffff) all inputs or inputs(0x0000) all outputs.
While levels() will only affect output pins, pullups() will only affect the levels of input pins.
Using an MCP23017 port expander module you can not only access individual pins.
You can also instantiate the following modules passing the mcp instance as the first argument:
- Input:
input = Input(mcp, pin) - Output:
output = Output(mcp, pin) - Linear motor:
motor = LinearMotor(mcp, move_in, move_out, end_in, end_out)
The pins pin, move_in, move_out, end_in and end_out are numbers from 0 to 15 referring to A0...A7 and B0...B7 on the MCP23017.
IMU¶
The IMU module provides access to a Bosch BNO055 9-axis absolute orientation sensor. Currently, only reading the accelerometer is implemented.
| Constructor | Description | Arguments |
|---|---|---|
imu = Imu([port[, sda[, scl[, address[, clk_speed]]]]]) |
See below | ints |
The constructor expects up to five arguments:
port: 0 or 1, since the ESP32 has two I2C ports (default: 0)sda: SDA pin (default: 21)scl: SCL pin (default: 22)address: client address of the MCP (0x28 or 0x29, default: 0x28)clk_speed: I2C clock speed (default: 100000)
| Properties | Description | Data type |
|---|---|---|
imu.cal_sys |
calibration: system (0 to 3) | int |
imu.cal_gyr |
calibration: gyroscope (0 to 3) | int |
imu.cal_acc |
calibration: accelerometer (0 to 3) | int |
imu.cal_mag |
calibration: magnetometer (0 to 3) | int |
imu.acc_x |
acceleration incl. gravity: x direction (m/s^2) | float |
imu.acc_y |
acceleration incl. gravity: y direction (m/s^2) | float |
imu.acc_z |
acceleration incl. gravity: z direction (m/s^2) | float |
imu.mag_x |
magnetic field strength: x direction (µT) | float |
imu.mag_y |
magnetic field strength: y direction (µT) | float |
imu.mag_z |
magnetic field strength: z direction (µT) | float |
imu.gyr_x |
gyroscope: x direction (degrees/s) | float |
imu.gyr_y |
gyroscope: y direction (degrees/s) | float |
imu.gyr_z |
gyroscope: z direction (degrees/s) | float |
imu.yaw |
orientation: Euler angle yaw (degrees) | float |
imu.roll |
orientation: Euler angle roll (degrees) | float |
imu.pitch |
orientation: Euler angle pitch (degrees) | float |
imu.quat_w |
orientation: quaternion component w | float |
imu.quat_x |
orientation: quaternion component x | float |
imu.quat_y |
orientation: quaternion component y | float |
imu.quat_z |
orientation: quaternion component z | float |
imu.lin_x |
acceleration excl. gravity: x direction (m/s^2) | float |
imu.lin_y |
acceleration excl. gravity: y direction (m/s^2) | float |
imu.lin_z |
acceleration excl. gravity: z direction (m/s^2) | float |
imu.grav_x |
gravity: x direction (m/s^2) | float |
imu.grav_y |
gravity: y direction (m/s^2) | float |
imu.grav_z |
gravity: z direction (m/s^2) | float |
imu.temp |
temperature (degrees Celsius) | int |
imu.data_select |
data selection | int |
The data_select property can be used to select which data is read from the IMU.
The default value is 0xffff, which means all data is read.
The following bits are available:
- 0x0001: calibration status
- 0x0002: accelerometer data
- 0x0004: magnetometer data
- 0x0008: gyroscope data
- 0x0010: Euler angles
- 0x0020: quaternion
- 0x0040: linear acceleration
- 0x0080: gravity
- 0x0100: temperature
The IMU is read in a background task, so the properties hold the newest completed sample. While reading fails, an error is printed at most once per second and the properties keep their last values. A message is printed when reading works again.
| Methods | Description | Arguments |
|---|---|---|
imu.set_mode(mode) |
Set operation mode of the IMU | str |
The mode parameter can be one of the following:
| Mode | Accel | Mag | Gyro | Relative Orientation | Absolute Orientation |
|---|---|---|---|---|---|
configmode |
- | - | - | - | - |
acconly |
X | - | - | - | - |
magonly |
- | X | - | - | - |
gyroonly |
- | - | X | - | - |
accmag |
X | X | - | - | - |
accgyro |
X | - | X | - | - |
maggyro |
- | X | X | - | - |
amg |
X | X | X | - | - |
imu |
X | - | X | X | - |
compass |
X | X | - | - | X |
m4g |
X | X | X | - | |
ndof_fmc_off |
X | X | X | - | X |
ndof |
X | X | X | - | X |
In non-fusion modes (acconly, magonly, gyroonly, accmag, accgyro, maggyro, amg),
the sensor signals (Accel, Mag, Gyro) are uncompensated and fusion data (Relative and Absolute Orientation) is not available.
In fusion modes (imu, compass, m4g, ndof_fmc_off, ndof),
the sensor signals (Accel, Mag, Gyro) are compensated and fusion data (Relative and Absolute Orientation) is available.
Note that the individual sensors need to be calibrated before the compensated and fused data is accurate.
| Sensor | Calibration |
|---|---|
| Accelerometer | Position the sensor in 6 different stable orientations |
| Magnetometer | Move the sensor in a figure-8 pattern in space |
| Gyroscope | Keep the sensor still for a few seconds |
IMU BNO085¶
The IMU BNO085 module provides access to a Bosch BNO085 9-axis absolute orientation sensor over the shared I²C bus. This module uses the same API as the IMU module but offers improved fusion quality and additional reports.
Note: Only one ImuBno085 instance can be active at a time due to hardware abstraction layer constraints.
| Constructor | Description | Arguments |
|---|---|---|
imu = ImuBno085([port[, sda[, scl[, int[, rst[, address[, clk]]]]]]]) |
See below | ints |
The constructor expects up to seven arguments:
port: I²C port number (default: 0)sda: SDA pin (default matches target, e.g. 21 on ESP32)scl: SCL pin (default matches target, e.g. 22 on ESP32)int: Interrupt pin (default: 26 on ESP32, none on ESP32-S3)rst: Reset pin (default: 32 on ESP32, none on ESP32-S3)address: I²C address (default: 0x4A)clk: I²C clock in Hz (default: 400000)
The properties and methods are similar to the IMU module.
The BNO085 offers improved accuracy and better sensor fusion algorithms compared to the BNO055.
Unlike the BNO055 module, euler angles (yaw, roll, pitch) are not computed on-device —
only quaternion output (quat_w/x/y/z) is provided.
Euler conversion should be done upstream.
The gyroscope (gyr_x/y/z) is reported in rad/s (the SH2 calibrated gyroscope report), not degrees/s as on the BNO055.
| Methods | Description | Arguments |
|---|---|---|
imu.set_mode(mode) |
Set operation mode of the IMU | str |
The mode parameter supports the same modes as the IMU module, except ndof_fmc_off (use ndof instead).
The configured mode is automatically restored if the BNO085 resets during operation.
Data Select
The data_select property is a bitmask that controls which sensor values are updated each step.
It defaults to 0xffff (all enabled).
Set individual bits to 0 to skip costly updates you don't need.
| Bit | Value | Data |
|---|---|---|
| 0 | 0x0001 |
Calibration (cal_sys/gyr/acc/mag) |
| 1 | 0x0002 |
Accelerometer (acc_x/y/z) |
| 2 | 0x0004 |
Magnetometer (mag_x/y/z) |
| 3 | 0x0008 |
Gyroscope (gyr_x/y/z) |
| 4 | 0x0010 |
Quaternion (quat_w/x/y/z) |
| 5 | 0x0020 |
Linear acceleration (lin_x/y/z) |
| 6 | 0x0040 |
Gravity (grav_x/y/z) |
| 7 | 0x0080 |
Temperature (temp) |
Differences to BNO055
The calibration properties (cal_sys, cal_gyr, cal_acc, cal_mag) use the same 0–3 range as the BNO055,
but the meaning differs:
| Value | BNO055 | BNO085 |
|---|---|---|
| 0 | Not calibrated | Unreliable |
| 1 | Partially calibrated | Low accuracy |
| 2 | Mostly calibrated | Medium accuracy |
| 3 | Fully calibrated | High accuracy (fully calibrated) |
On the BNO055, cal_sys, cal_gyr, cal_acc, and cal_mag are read together in a single calibration register.
On the BNO085, each calibration value is derived from the accuracy status of its corresponding sensor report
(e.g. cal_acc is updated when an accelerometer event arrives, cal_sys when a rotation vector event arrives).
This means calibration values only update while the corresponding sensor report is enabled via set_mode.
CAN interface¶
The CAN module allows communicating with peripherals on the specified CAN bus.
| Constructor | Description | Arguments |
|---|---|---|
can = Can(rx, tx, baud) |
RX/TX pins and baud rate | int, int, int |
| Methods | Description | Arguments |
|---|---|---|
can.send(node_id, d0, d1, d2, d3, d4, d5, d6, d7) |
Send a frame with 8 data bytes | 9x int |
can.output_extended(mask, code) |
Print matching 29-bit frames | 2x int |
can.get_status() |
Print the driver status | |
can.start() |
Start the driver | |
can.stop() |
Stop the driver | |
can.reset() |
Reset the driver |
IDs above 0x7FF are sent as extended (29-bit) frames, IDs above 0x1FFFFFFF are rejected.
An extended frame with an ID up to 0x7FF cannot be sent; send puts such an ID into a standard frame.
Received extended frames never reach other modules, which subscribe to 11-bit IDs only.
output_extended(mask, code) prints every extended frame with (id & mask) == code in the same format as the module's output; it can be called several times to add more filters, and code must not have bits outside mask.
can.mute() also removes all output_extended filters; unmute() does not bring them back.
Extended frames are always printed with an 8-digit hex ID, also after unmute(), so can 00000123,… is an extended and can 123,… a standard frame.
The method get_status() prints the following information:
state("STOPPED", "RUNNING", "BUS_OFF" or "RECOVERING"),msgs_to_tx,msgs_to_rx,tx_error_counter,rx_error_counter,tx_failed_count,rx_missed_count,rx_overrun_count,arb_lost_countandbus_error_count.
After creating a CAN module, the driver is started automatically.
The start() and stop() methods are primarily for debugging purposes.
The reset() method will stop the driver, try to recover it and then start it again.
It can be used to recover the driver from a "BUS_OFF" state.
The module does the same by itself while the bus is "BUS_OFF", at most once per second.
It prints "CAN bus running again" once the bus has stayed out of "BUS_OFF" for a second.
Each reset sets the counters of get_status() back to zero.
Serial interface¶
The serial module allows communicating with peripherals via the specified connection.
| Constructor | Description | Arguments |
|---|---|---|
serial = Serial(rx, tx, baud, num) |
RX/TX pins, baud rate, UART number | 4x int |
| Methods | Description | Arguments |
|---|---|---|
serial.send(b0, b1, b2, ...) |
Send a number of bytes | ints |
serial.read() |
Read and output current buffer |
This module might be used by other modules that communicate with peripherals via serial. You can, however, unmute the serial module to have incoming messages printed to the command line instead of keeping them buffered for other modules. An unmuted module prints one line per batch of bytes the hardware hands over, so a sender that pauses between its messages gets one line per message. A line carries at most 85 bytes; the rest of a longer batch follows on the next line.
The UART number and its pins stay reserved for the serial module until the core restarts, also after Expander.disconnect().
A serial on UART0 with the console's pins can only carry a serial bus, which takes over the console (see Console as Link); its own methods fail.
JBD BMS¶
The JBD BMS module reads a battery management system with the JBD protocol (frames from 0xDD to 0x77) over a serial, usually at 9600 baud.
| Constructor | Description | Arguments |
|---|---|---|
bms = JbdBms(serial) |
Serial module wired to the BMS | Serial |
| Properties | Description | Data type |
|---|---|---|
bms.voltage |
Total voltage (V) | float |
bms.current |
Current (A), positive while charging | float |
bms.residual_capacity |
Remaining capacity (Ah) | float |
bms.nominal_capacity |
Nominal capacity (Ah) | float |
bms.percentage |
State of charge (%) | int |
bms.cycles |
Charge cycles | int |
bms.temperature |
Mean of the temperature sensors (°C) | float |
bms.protections |
Protection flags (see below) | int |
bms.fets |
MOSFETs that are on: charging (bit 0), discharging (bit 1) | int |
bms.cells |
Number of cells | int |
bms.interval |
Time between requests (s), 0 to stop them | float |
bms.last_message_age |
Time since the values were last updated (ms) | int |
bms.errors |
Answers that were missing or invalid | int |
| Methods | Description | Arguments |
|---|---|---|
bms.cell_voltages() |
Ask for the cell voltages and print them (V) | |
bms.hardware_version() |
Ask for the hardware version and print it |
The module asks for the basic information every interval seconds, 1 s by default, and updates the properties with each valid answer.
Until the first valid answer with the basic information, the values of the BMS are 0 and last_message_age counts from the boot, like core.last_message_age.
An answer that is missing after 500 ms or invalid, e.g. with a wrong checksum or an error status, counts in errors, and the properties keep their last values.
If the answer to a method is missing or invalid, the module also prints a warning, e.g. warning: bms got no cell voltages.
Keep the serial muted, since the module reads its bytes.
The bits of protections are:
- bit 0: cell over-voltage,
- bit 1: cell under-voltage,
- bit 2: battery over-voltage,
- bit 3: battery under-voltage,
- bit 4: charging over-temperature,
- bit 5: charging under-temperature,
- bit 6: discharging over-temperature,
- bit 7: discharging under-temperature,
- bit 8: charging over-current,
- bit 9: discharging over-current,
- bit 10: short circuit,
- bit 11: front-end IC error and
- bit 12: MOSFET software lock.
On a serial bus peer, the values can travel to the coordinator in telemetry frames:
bms_serial = Serial(26, 27, 9600, 2)
bms = JbdBms(bms_serial)
core.telemetry(bms.voltage, bms.current, bms.percentage, bms.temperature, bms.protections, 1000)
Linear motor¶
This module controls a linear actuator via two output pins (move in, move out) and two input pins reading two limit switches (end in, end out).
| Constructor | Description | Arguments |
|---|---|---|
motor = LinearMotor(move_in, move_out, end_in, end_out) |
motor control pins and limit switches | 4x int |
| Properties | Description | Data type |
|---|---|---|
motor.in |
Motor is in "in" position | bool |
motor.out |
Motor is in "out" position | bool |
motor.enabled |
Whether the motor is enabled | bool |
| Methods | Description |
|---|---|
motor.in() |
Move in |
motor.out() |
Move out |
motor.stop() |
Stop the motor |
motor.enable() |
Enable the motor |
motor.disable() |
Disable the motor |
When the motor is disabled, it will stop and ignore in/out commands.
ODrive Motor¶
The ODrive motor module controls a motor using an ODrive motor controller.
| Constructor | Description | Arguments |
|---|---|---|
motor = ODriveMotor(can, can_id[, version]) |
CAN module, node ID and version | CAN module, int, int |
The version parameter is an optional integer indicating the patch number of the ODrive firmware (4, 5 or 6; default: 4 for version "0.5.4").
Version 0.5.6 allows to read the motor error flag.
| Properties | Description | Data type |
|---|---|---|
motor.position |
Motor position (meters) | float |
motor.speed |
Motor speed (m/s) | float |
motor.tick_offset |
Encoder tick offset | float |
motor.m_per_tick |
Meters per encoder tick | float |
motor.reversed |
Reverse motor direction | bool |
motor.axis_state |
State of the motor axis | int |
motor.axis_error |
Error code of the axis | int |
motor.motor_error |
Motor error flat (requires version 0.5.6) | int |
motor.enabled |
Whether the motor is enabled | bool |
motor.motor_temperature |
Motor temperature (°C) | float |
motor.current |
Measured motor current Iq (A) | float |
motor.current_setpoint |
Commanded motor current Iq (A) | float |
The motor_temperature will only update if the firmware generated from the
zauberzeug/ODrive fork is installed on the ODrive.
Otherwise, the motor_temperature property will remain at 0.
The ODrive sends its current only when asked to, so current and current_setpoint stay at 0
until the periodic message is switched on for the axis — <axis>.config.can.iq_rate_ms (requires version 0.5.6)
defaults to 0 and is the interval in milliseconds.
| Methods | Description | Arguments |
|---|---|---|
motor.zero() |
Set current position as zero position | |
motor.power(torque) |
Move with given torque |
float |
motor.speed(speed) |
Move with given speed (m/s) |
float |
motor.position(position) |
Move to given position (m) |
float |
motor.limits(speed, current) |
Set speed (m/s) and current (A) limits | float, float |
motor.off() |
Turn motor off (idle state) | |
motor.reset_motor() |
Resets the motor and clears errors | |
motor.enable() |
Enable the motor | |
motor.disable() |
Disable the motor | |
motor.stop() |
Stop the motor |
When the motor is disabled, it will stop and ignore movement commands.
ODrive Wheels¶
The ODrive wheels module combines two ODrive motors and provides odometry and steering for differential wheeled robots.
| Constructor | Description | Arguments |
|---|---|---|
wheels = ODriveWheels(left_motor, left_motor) |
Two ODrive motor modules | two ODrive motor modules |
| Properties | Description | Data type |
|---|---|---|
wheels.width |
Wheel distance (m) | float |
wheels.max_wheel_speed |
Speed limit of the faster wheel in speed() (m/s, 0 = off) |
float |
wheels.linear_speed |
Forward speed (m/s) | float |
wheels.angular_speed |
Turning speed (rad/s) | float |
wheels.enabled |
Whether the wheels are enabled | bool |
wheels.locked |
Whether driving is blocked (safety interlock, see below) | bool |
wheels.drive_command_age |
Time since the last drive command (ms, see below) | int |
wheels.drive_command_timeout |
Stop when no drive command arrives for this long (s, 0 = off) | float |
| Methods | Description | Arguments |
|---|---|---|
wheels.power(left, right) |
Move with torque per wheel | float, float |
wheels.speed(linear, angular) |
Move with linear/angular speed (m/s, rad/s) |
float, float |
wheels.off() |
Turn both motors off (idle state) | |
wheels.enable() |
Enable both motors | |
wheels.disable() |
Disable both motors |
When the wheels are disabled, they will stop and ignore movement commands.
This allows disabling the wheels permanently by setting enabled = false in conjunction with calling the off() method.
Now the vehicle can be pushed manually with motors turned off, without taking care of every line of code potentially re-activating the motors.
max_wheel_speed caps speed() at what the drivetrain can do.
Driving and turning at once asks the outer wheel for more than either alone; if the drive cut off only that wheel, the robot would veer instead of following the requested curve.
So when the faster wheel would exceed max_wheel_speed, both wheels are scaled down together: the robot keeps its direction and curve radius and only gets slower.
power() is not limited.
A speed(0, 0) after motion is repeated about every 100 ms for one second, because a single stop can be lost on the bus or refused by a drive, which would leave a wheel creeping at its last setpoint.
A further speed(0, 0) restarts the repeat; any other speed(), power() or off() that goes through ends it early, and so do locked, a tripped dead man's switch and disabling the wheels, which hold or stop the wheels on their own.
Commands sent to the motors directly are not noticed and get overwritten within that second, so call wheels.off() rather than off() on each motor to idle them right after a stop.
The locked property is a safety interlock for rules running on the microcontroller:
while it is true, drive commands are ignored and the wheels are actively held at standstill with a zero-speed setpoint — the motors stay enabled.
This lets a rule block driving while some other condition is unmet, for example while a tool is not in its parking position.
The hold is sent when locked becomes true and refreshed about once per second, so it re-engages even if a motor controller restarts.
locked only blocks commands: disable() still switches the motors off, and a locked but switched-off robot can be pushed by hand.
While locked is true, off() does not stick — the hold re-engages within about a second; call disable() to switch the motors off durably.
Driving resumes as soon as locked is false again.
Writes to locked, enabled, drive_command_timeout and max_wheel_speed are forwarded to shadow modules, so shadowed wheels stop together with their master and keep to the same speed limit.
The drive_command_timeout property is a dead man's switch against lost or silent hosts:
after a non-zero speed() or power() command, the wheels stop on their own with a zero-speed setpoint once no further drive command arrived for drive_command_timeout seconds — the motors stay enabled.
The stop is always a zero speed, also after power(), so it switches the motors from torque to velocity control.
Only speed() and power() count as drive commands; enable(), off() and property writes do not, so they cannot keep a stale motion alive.
The stop is logged as a warning and held like locked holds: the zero-speed setpoint is refreshed about once per second, so a stop that did not reach the motors is re-asserted.
The next drive command releases the hold and re-arms the switch.
The default is 1 s, so a host has to repeat its drive command at least that often to keep driving.
Robots driven by a remote control should use a shorter timeout, and 0 disables the switch, e.g. on a test bench.
drive_command_age holds the time in milliseconds since the last drive command, whether it was applied or not, for rules that need finer control.
See Machine Safety for the background.
RMD Motor¶
The RMD motor module controls a MyActuator RMD motor via CAN.
| Constructor | Description | Arguments |
|---|---|---|
rmd = RmdMotor(can, motor_id, ratio) |
CAN module, motor ID (1..8) and transmission ratio | CAN module, int, int |
| Properties | Description | Data type |
|---|---|---|
rmd.position |
Multi-turn motor position (deg) | float |
rmd.torque |
Current torque | float |
rmd.speed |
Current speed (deg/s) | float |
rmd.temperature |
Current temperature (˚C) | float |
rmd.can_age |
Time since last CAN message from motor (s) | float |
rmd.enabled |
Whether the motor is enabled | bool |
| Methods | Description | Arguments |
|---|---|---|
rmd.power(torque) |
Move with given torque (-32..32 A) |
float |
rmd.speed(speed) |
Move with given speed (deg/s) |
float |
rmd.position(pos) |
Move to and hold at pos (deg) |
float |
rmd.position(pos, speed) |
Move to and hold at pos (deg) with max. speed (deg/s) |
float, float |
rmd.stop() |
Stop motor (but keep operating state) | |
rmd.off() |
Turn motor off (clear operating state) | |
rmd.hold() |
Hold current position | |
rmd.get_pid() |
Print PID parameters Kp/Ki for position/speed/torque loop | |
rmd.set_pid(...) |
Set PID parameters Kp/Ki for position/speed/torque loop | 6x int |
rmd.get_acceleration() |
Print acceleration (deg/s^2) | |
rmd.set_acceleration(...) |
Set accelerations/decelerations for position/speed loop (deg/s^2) | 4x int |
rmd.get_status() |
Print temperature [˚C], voltage [V] and motor error code | |
rmd.clear_errors() |
Clear motor error | |
rmd.enable() |
Enable the motor | |
rmd.disable() |
Disable the motor |
When the motor is disabled, it will stop and ignore movement commands.
Set acceleration
Although get_acceleration() prints only one acceleration per motor, set_acceleration distinguishes the following four parameters:
- acceleration for position mode
- deceleration for position mode
- acceleration for speed mode
- deceleration for speed mode
You can pass 0 to skip parameters, i.e. to keep individual acceleration values unchanged.
RMD Motor Pair¶
The RMD motor pair module allows to synchronize two RMD motors.
| Constructor | Description | Arguments |
|---|---|---|
rmd = RmdPair(rmd1, rmd2) |
Two RMD motor modules | 2x RMD Motor module |
| Properties | Description | Data type |
|---|---|---|
rmd.v_max |
Maximum speed (deg/s, default: 360) | float |
rmd.a_max |
Maximum acceleration (deg/s² (default: 10000) | float |
rmd.enabled |
Whether the motor pair is enabled | bool |
| Methods | Description | Arguments |
|---|---|---|
rmd.move(x, y) |
Move motor 1 to x and motor 2 to x |
2x float |
rmd.stop() |
Stop motors (but keep operating state) | |
rmd.off() |
Turn motors off (clear operating state) | |
rmd.hold() |
Hold current positions | |
rmd.clear_errors() |
Clear motor errors | |
rmd.enable() |
Enable both motors | |
rmd.disable() |
Disable both motors |
When the motor pair is disabled, it will stop both motors and ignore movement commands.
RoboClaw¶
The RoboClaw module serves as building block for more complex modules like RoboClaw motors. It communicates with a Basicmicro RoboClaw motor driver via serial.
| Constructor | Description | Arguments |
|---|---|---|
claw = RoboClaw(serial, address) |
Serial module and address | Serial module, int |
| Properties | Description | Data type |
|---|---|---|
claw.temperature |
Board temperature (degrees Celsius) | float |
The temperature property is updated every 1 second.
RoboClaw Motor¶
The RoboClaw motor module controls a motor using a RoboClaw module.
| Constructor | Description | Arguments |
|---|---|---|
motor = RoboClawMotor(claw, motor_id) |
RoboClaw module and motor ID (1..2) | RoboClaw module, int |
| Properties | Description | Data type |
|---|---|---|
motor.position |
Multi-turn motor position (encoder ticks) | int |
motor.enabled |
Whether the motor is enabled | bool |
| Methods | Description | Arguments |
|---|---|---|
motor.power(torque) |
Move with given torque (-1..1) |
float |
motor.speed(speed) |
Move with given speed (-32767..32767) |
float |
motor.zero() |
Store position as zero position | |
motor.enable() |
Enable the motor | |
motor.disable() |
Disable the motor |
When the motor is disabled, it will stop and ignore movement commands.
RoboClaw Wheels¶
The RoboClaw wheels module combines two RoboClaw motors and provides odometry and steering for differential wheeled robots.
| Constructor | Description | Arguments |
|---|---|---|
wheels = RoboClawWheels(left_motor, left_motor) |
left and right motors | two RoboClaw motor modules |
| Properties | Description | Data type |
|---|---|---|
wheels.width |
Wheel distance (m) | float |
wheels.max_wheel_speed |
Speed limit of the faster wheel in speed() (m/s, 0 = off) |
float |
wheels.linear_speed |
Forward speed (m/s) | float |
wheels.angular_speed |
Turning speed (rad/s) | float |
wheels.m_per_tick |
Meters per encoder tick | float |
wheels.enabled |
Whether motors react to commands | bool |
wheels.locked |
Whether driving is blocked (safety interlock, see below) | bool |
wheels.drive_command_age |
Time since the last drive command (ms, see below) | int |
wheels.drive_command_timeout |
Stop when no drive command arrives for this long (s, 0 = off) | float |
| Methods | Description | Arguments |
|---|---|---|
wheels.power(left, right) |
Move with torque per wheel (-1..1) | float, float |
wheels.speed(linear, angular) |
Move with linear/angular speed (m/s, rad/s) |
float, float |
wheels.off() |
Turn both motors off (idle state) | |
wheels.enable() |
Enable both motors | |
wheels.disable() |
Disable both motors |
When the wheels are disabled, they will stop and ignore movement commands.
max_wheel_speed caps speed() at what the drivetrain can do.
Driving and turning at once asks the outer wheel for more than either alone; if the drive cut off only that wheel, the robot would veer instead of following the requested curve.
So when the faster wheel would exceed max_wheel_speed, both wheels are scaled down together: the robot keeps its direction and curve radius and only gets slower.
power() is not limited.
A speed(0, 0) after motion is repeated about every 100 ms for one second, because a single stop can be lost on the bus or refused by a drive, which would leave a wheel creeping at its last setpoint.
A further speed(0, 0) restarts the repeat; any other speed(), power() or off() that goes through ends it early, and so do locked, a tripped dead man's switch and disabling the wheels, which hold or stop the wheels on their own.
Commands sent to the motors directly are not noticed and get overwritten within that second.
The locked property is a safety interlock for rules running on the microcontroller:
while it is true, drive commands are ignored and the wheels are actively held at standstill with a zero-speed setpoint — the motors stay enabled.
This lets a rule block driving while some other condition is unmet, for example while a tool is not in its parking position.
The hold is sent when locked becomes true and refreshed about once per second, so it re-engages even if a motor controller restarts.
locked only blocks commands: disable() still switches the motors off, and a locked but switched-off robot can be pushed by hand.
While locked is true, off() does not stick — the hold re-engages within about a second; call disable() to switch the motors off durably.
Driving resumes as soon as locked is false again.
Writes to locked, enabled, drive_command_timeout and max_wheel_speed are forwarded to shadow modules, so shadowed wheels stop together with their master and keep to the same speed limit.
The drive_command_timeout property is a dead man's switch against lost or silent hosts:
after a non-zero speed() or power() command, the wheels stop on their own with a zero-speed setpoint once no further drive command arrived for drive_command_timeout seconds — the motors stay enabled.
The stop is always a zero speed, also after power(), so it switches the motors from torque to velocity control.
Only speed() and power() count as drive commands; enable(), off() and property writes do not, so they cannot keep a stale motion alive.
The stop is logged as a warning and held like locked holds: the zero-speed setpoint is refreshed about once per second, so a stop that did not reach the motors is re-asserted.
The next drive command releases the hold and re-arms the switch.
The default is 1 s, so a host has to repeat its drive command at least that often to keep driving.
Robots driven by a remote control should use a shorter timeout, and 0 disables the switch, e.g. on a test bench.
drive_command_age holds the time in milliseconds since the last drive command, whether it was applied or not, for rules that need finer control.
See Machine Safety for the background.
Stepper Motor¶
The stepper motor module controls a stepper motor via "step" and "direction" pins. It uses the ESP LED Control API to generate pulses with sufficiently high frequencies and the Pulse Counter API to count steps.
| Constructor | Description | Arguments |
|---|---|---|
motor = StepperMotor(step, dir[, lt[, lc]]) |
Step and direction pins | 2–4x int |
The constructor arguments lt (LEDC timer) and lc (LEDC channel) are optional and default to 0.
When using multiple stepper motors, set different timer/channel pairs to avoid conflicts.
The pulse counter used for position feedback is created internally.
| Properties | Description | Data type |
|---|---|---|
motor.position |
Motor position (steps) | int |
motor.speed |
Motor speed (steps per second) | int |
motor.idle |
Motor idle state | bool |
motor.enabled |
Whether the motor is enabled | bool |
| Methods | Description | Arguments |
|---|---|---|
motor.speed(speed[, acceleration]) |
Move with given speed |
2x float |
motor.position(position, speed[, acceleration]) |
Move to given position |
3x float |
motor.stop() |
Stop | |
motor.enable() |
Enable the motor | |
motor.disable() |
Disable the motor |
The optional acceleration argument defaults to 0, which starts and stops pulsing immediately.
When the motor is disabled, it will stop and ignore movement commands.
MKS Servo Motor¶
The MKS Servo Motor module controls an MKS SERVO42D/57D closed-loop stepper motor via CAN.
| Constructor | Description | Arguments |
|---|---|---|
motor = MksServoMotor(can, can_id) |
CAN module and CAN node ID | CAN module, int |
| Properties | Description | Data type |
|---|---|---|
motor.position |
Motor position (degrees) | float |
motor.speed |
Motor speed (RPM) | int |
motor.working_current |
Working current (mA, 0-3000, default: 1700) | int |
motor.enabled |
Whether the motor is enabled | bool |
motor.position_error |
Last read position error (degrees) | float |
motor.set_mode_status |
Result of the last set_mode (0 = OK, 1 = failed, 2 = pending) |
int |
| Methods | Description | Arguments |
|---|---|---|
motor.enable() |
Enable the motor | |
motor.disable() |
Disable the motor | |
motor.set_mode(mode) |
Set working mode (see working modes) | int |
motor.zero() |
Set current position as zero | |
motor.set_working_current(ma) |
Set working current (mA, 0-3000) | int |
motor.set_holding_current(pct) |
Set holding current as percentage of working current (10-100 in steps of 10) | int |
motor.set_bitrate(hz) |
Set CAN bitrate in Hz (125000, 250000, 500000 or 1000000) | int |
motor.set_can_id(id) |
Set motor's CAN ID (1-2047) | int |
motor.position(degrees, speed, acc) |
Move to absolute position (degrees, RPM, acceleration) | float, int, int |
motor.speed(speed, direction, acc) |
Run motor continuously (0-3000 RPM, direction, acceleration) | int, int, int |
motor.stop(acc) |
Stop motor with given deceleration (0-255) | int |
motor.read_position_error() |
Request position error from motor via CAN |
The position() method moves the motor to an absolute coordinate position (in degrees from the zero point)
with a given speed in RPM (0-3000) and acceleration (0-255).
The speed() method accepts a speed in RPM (0-3000), direction (0: CCW, 1: CW) and acceleration (0-255).
The acceleration parameter controls the ramp rate: higher values mean faster acceleration.
If acceleration is 0, the motor runs directly at the set speed without ramping.
The stop() method decelerates and stops the motor with the given acceleration (0-255).
If acceleration is 0, the motor stops immediately.
The read_position_error() method requests the current position error from the motor via CAN.
The result is available in the position_error property (in degrees) once the motor responds.
The position and speed properties are read in turns, so each of them is updated every other step.
On construction, the module switches off the motor's answers to speed and position commands (command 0x8C),
including the status the motor would otherwise send when a move or a stop completes.
The motor keeps answering read and configuration commands.
The set_bitrate() method changes the CAN bitrate on the motor.
The rate is given in Hz and must be one of the four supported values (125000, 250000, 500000 or 1000000);
any other value is rejected with a log message and no command is sent.
The motor switches to the new bitrate immediately, which means communication with the motor is lost
until the Lizard CAN bus is also reconfigured to match the new bitrate.
The set_can_id() method changes the motor's CAN ID (range 1-2047, default 1).
The new ID is persisted on the drive, so the motor only responds on the new ID afterwards —
the Lizard script must be updated to construct the module with the new can_id.
ID 0 is reserved as the broadcast address (all motors listen, none respond) and is therefore not accepted here.
Working Modes
The MKS SERVO42D/57D supports the following working modes:
| Mode | Name | Description | Remark |
|---|---|---|---|
| 0x00 | CR_OPEN | Pulse interface open-loop mode | |
| 0x01 | CR_CLOSE | Pulse interface closed-loop mode | |
| 0x02 | CR_vFOC | Pulse interface FOC mode | default |
| 0x03 | SR_OPEN | Bus interface open-loop mode | |
| 0x04 | SR_CLOSE | Bus interface closed-loop mode | |
| 0x05 | SR_vFOC | Bus interface FOC mode |
The set_mode() method sets the working mode of the motor.
For CAN bus control, use SR_vFOC mode (0x05): motor.set_mode(5).
The constructor automatically sets SR_vFOC mode (0x05),
which is required for the bus motion commands (position(), speed(), stop()).
Motor Axis¶
The motor axis module wraps a motor and two limit switches. It prevents the motor from moving past the limits. But in contrast to a simple Lizard rule, it allows to actively move out of the limits when moving in the right direction. Currently supported motor types are CanOpenMotor, ODriveMotor and StepperMotor.
| Constructor | Description | Arguments |
|---|---|---|
axis = MotorAxis(motor, limit1, limit2) |
motor and input modules | 3 modules |
| Properties | Description | Data type |
|---|---|---|
axis.enabled |
Whether the motor axis is enabled | bool |
To get the current position or speed, access the motor module instead.
| Methods | Description | Arguments |
|---|---|---|
axis.speed(speed[, acceleration]) |
Move with given speed |
2x float |
axis.position(position, speed[, acceleration]) |
Move to given position |
3x float |
axis.stop() |
Stop | |
axis.enable() |
Enable the motor axis | |
axis.disable() |
Disable the motor axis |
When the motor axis is disabled, it will stop the motor and ignore movement commands.
CanOpenMaster¶
The CanOpenMaster module sends periodic SYNC messages to all CANopen nodes.
At creation, no messages are sent until sync_interval is set to a value greater than 0.
A CanOpenMaster on the same CAN bus is required for CanOpenMotor — without periodic SYNC messages, position, velocity and status properties will not update. Other CAN motor modules (D1Motor, DunkerMotor) do not need a CanOpenMaster.
| Constructor | Description | Arguments |
|---|---|---|
co_master = CanOpenMaster(can) |
CAN module | CAN module |
| Properties | Description | Data type |
|---|---|---|
co_master.sync_interval |
Amount of lizard steps in between each SYNC | int |
CanOpenMotor¶
The CanOpenMotor module implements a subset of commands necessary to control a motor implementing DS402. Positional and velocity units are currently undefined and must be manually measured. Once the configuration sequence has finished, current status, position and velocity are queried on every SYNC.
A CanOpenMaster on the same CAN bus is needed for position, velocity and status updates.
| Constructor | Description | Arguments |
|---|---|---|
motor = CanOpenMotor(can, node_id) |
CAN module and node ID (1..127) | CAN module, int |
| Methods | Description | Arguments |
|---|---|---|
motor.enter_pp_mode(velo) |
Set 402 operating mode to profile position, halt off, and target velocity to velo |
int |
motor.enter_pv_mode(velo) |
Set 402 operating mode to profile velocity, halt on, and target velocity to velo |
int |
motor.set_target_position(pos) |
Set target position to pos (signed). [pp mode] |
int |
motor.commit_target_position() |
Instruct motor to move to previously set target position. [pp mode] | |
motor.set_target_velocity(velo) |
Set target velocity to velo. Absolute for pp mode, signed for pv mode |
int |
motor.set_ctrl_halt(mode) |
Latches / resets the "halt" bit and sends the updated control word to the node | bool |
motor.set_ctrl_enable(mode) |
Latches / resets the "enable operation" bit and sends an updated control word to the node | bool |
motor.set_profile_acceleration(acceleration) |
Sets the motor acceleration | int |
motor.set_profile_deceleration(deceleration) |
Sets the motor deceleration | int |
motor.set_profile_quick_stop_deceleration(deceleration) |
Sets the motor deceleration for the quick stop command | int |
motor.reset_fault() |
Clear any faults (like positioning errors). Implicitly sets the "halt" bit. | |
motor.sdo_read(index) |
Performs an SDO read at index index and sub index 0x00 |
int |
| Properties | Description | Data type |
|---|---|---|
initialized |
Concurrent init sequence has finished, motor is ready | bool |
last_heartbeat |
Time in µs since bootup when last heartbeat was received | int |
is_booting |
Node is in booting state | bool |
is_preoperational |
Node is in pre-operational state | bool |
is_operational |
Node is in operational state | bool |
actual_position |
Motor position at last SYNC | int |
position_offset |
Offset implicitly added to target/reported position | int |
actual_velocity |
Motor velocity at last SYNC | int |
status_enabled |
Operation enabled bit of status word since last SYNC | bool |
status_fault |
Fault bit of status word since last SYNC | bool |
status_target_reached |
Target reached bit of status word since last SYNC | bool |
pp_set_point_acknowledge |
Set point acknowledge bit (profile position mode) | bool |
pv_is_moving |
Motor is moving (profile velocity mode) | bool |
ctrl_enable |
Latched operation enable bit of every sent control word | bool |
ctrl_halt |
Latched halt bit of every sent control word | bool |
enabled |
Whether the motor is enabled | bool |
Configuration sequence
After creation of the module, the configuration is stepped through automatically on each heartbeat; once finished, the initialized attribute is set to true.
Target position sequence
Note: The target velocity must be positive regardless of target point direction. The halt bit is cleared when entering pp, though it can be set at any point during moves to effectively apply brakes.
// First time, assuming motor is disabled and not in pp mode
motor.set_ctrl_enable(true)
motor.enter_pp_mode(<some positive velocity>)
// All further set points only need these
motor.set_target_position(<some position>)
motor.commit_target_position()
Target velocity sequence
Unlike in the profile position mode, here the sign of the velocity does controls the direction. The halt bit is set when entering pv. To start moving, clear it (and set again to stop).
// First time, assuming motor is disabled and not in pv mode
motor.set_ctrl_enable(true)
motor.enter_pv_mode(<some signed velocity>)
// Further movements only need these
motor.set_ctrl_halt(false)
// await some condition
motor.set_ctrl_halt(true)
D1 Motor¶
This module controls an igus D1 motor controller via CANOpen.
| Constructor | Description | Arguments |
|---|---|---|
motor = D1Motor(can, node_id) |
CAN module and node ID (1..127) | CAN module, int |
| Properties | Description | Data type |
|---|---|---|
motor.switch_search_speed |
Speed for moving into the end stop | int |
motor.zero_search_speed |
Speed for moving out ot the end stop | int |
motor.homing_acceleration |
Acceleration for homing | int |
motor.profile_acceleration |
Acceleration for profile movements | int |
motor.profile_velocity |
Velocity for profile position movements | int |
motor.profile_deceleration |
Deceleration for profile movements | int |
motor.position |
Current position | int |
motor.velocity |
Current velocity | int |
motor.status_word |
Status word | int |
motor.status_flags |
Status flags | int |
motor.enabled |
Whether the motor is enabled | bool |
Bit 0 of the status flags indicates the motor is referenced (1) or not (0).
The status word (also called "Statusword") is a 16 bit integer with several flags. See the D1 manual for details.
| Methods | Description | Arguments |
|---|---|---|
motor.setup() |
Setup (enable) the motor | |
motor.home() |
Start homing the motor | |
motor.profile_position() |
Move to given position | int |
motor.profile_velocity() |
Move with given velocity | int |
motor.stop() |
Stop (disable) the motor | |
motor.reset() |
Reset motor errors | |
motor.sdo_read(index[, subindex]) |
Read SDO | 2x int |
motor.sdo_write(index, subindex, bits, value) |
Write SDO | 4x int |
motor.nmt_write() |
Write NMT | int |
motor.enable() |
Enable the motor | |
motor.disable() |
Disable the motor |
When the motor is disabled, it will stop and ignore movement commands.
DunkerMotor¶
This module controls dunkermotoren motor via CANOpen.
| Constructor | Description | Arguments |
|---|---|---|
motor = DunkerMotor(can, node_id) |
CAN module and node ID (1..127) | CAN module, int |
| Properties | Description | Data type |
|---|---|---|
motor.speed |
Motor speed (meters per second) | float |
motor.voltage_logic |
Voltage logic (V) | float |
motor.voltage_power |
Voltage power (V) | float |
motor.m_per_turn |
Meters per turn | float |
motor.reversed |
Reverse motor direction | bool |
motor.enabled |
Whether the motor is enabled | bool |
Note: To reduce bandwidth, voltages are only queried when explicitly requested by calling update_voltages().
| Methods | Description | Arguments |
|---|---|---|
motor.speed(speed) |
Move with given speed (m/s) |
float |
motor.enable() |
Enable motor | |
motor.disable() |
Disable motor | |
motor.sdo_read(index[, subindex]) |
Read SDO | 2x int |
motor.sdo_write(index, subindex, bits, value) |
Write SDO | 4x int |
motor.update_voltages() |
Update voltages |
When the motor is disabled, it will freewheel and ignore movement commands.
DunkerWheels¶
The DunkerWheels module combines two DunkerMotor modules and provides odometry and steering for differential wheeled robots.
| Constructor | Description | Arguments |
|---|---|---|
wheels = DunkerWheels(left_motor, right_motor) |
left and right motors | two DunkerMotor modules |
| Properties | Description | Data type |
|---|---|---|
wheels.width |
Wheel distance (m) | float |
wheels.max_wheel_speed |
Speed limit of the faster wheel in speed() (m/s, 0 = off) |
float |
wheels.linear_speed |
Forward speed (m/s) | float |
wheels.angular_speed |
Turning speed (rad/s) | float |
wheels.enabled |
Whether the wheels are enabled | bool |
wheels.locked |
Whether driving is blocked (safety interlock, see below) | bool |
wheels.drive_command_age |
Time since the last drive command (ms, see below) | int |
wheels.drive_command_timeout |
Stop when no drive command arrives for this long (s, 0 = off) | float |
| Methods | Description | Arguments |
|---|---|---|
wheels.speed(linear, angular) |
Move with linear/angular speed (m/s, rad/s) |
float, float |
wheels.enable() |
Enable both motors | |
wheels.disable() |
Disable both motors |
When the wheels are disabled, they will freewheel and ignore movement commands.
max_wheel_speed caps speed() at what the drivetrain can do.
Driving and turning at once asks the outer wheel for more than either alone; if the drive cut off only that wheel, the robot would veer instead of following the requested curve.
So when the faster wheel would exceed max_wheel_speed, both wheels are scaled down together: the robot keeps its direction and curve radius and only gets slower.
A speed(0, 0) after motion is repeated about every 100 ms for one second, because a single stop can be lost on the bus or refused by a drive, which would leave a wheel creeping at its last setpoint.
A further speed(0, 0) restarts the repeat; a non-zero speed() that goes through ends it early, and so do locked, a tripped dead man's switch and disabling the wheels, which hold or stop the wheels on their own.
Commands sent to the motors directly are not noticed and get overwritten within that second.
The locked property is a safety interlock for rules running on the microcontroller:
while it is true, drive commands are ignored and the wheels are actively held at standstill with a zero-speed setpoint — the motors stay enabled.
This lets a rule block driving while some other condition is unmet, for example while a tool is not in its parking position.
The hold is sent when locked becomes true and refreshed about once per second, so it re-engages even if a motor controller restarts.
locked only blocks commands: disable() still switches the motors off, and a locked but switched-off robot can be pushed by hand.
Driving resumes as soon as locked is false again.
Writes to locked, enabled, drive_command_timeout and max_wheel_speed are forwarded to shadow modules, so shadowed wheels stop together with their master and keep to the same speed limit.
The drive_command_timeout property is a dead man's switch against lost or silent hosts:
after a non-zero speed() command, the wheels stop on their own with a zero-speed setpoint once no further drive command arrived for drive_command_timeout seconds — the motors stay enabled.
Only speed() counts as a drive command; enable() and property writes do not, so they cannot keep a stale motion alive.
The stop is logged as a warning and held like locked holds: the zero-speed setpoint is refreshed about once per second, so a stop that did not reach the motors is re-asserted.
The next drive command releases the hold and re-arms the switch.
The default is 1 s, so a host has to repeat its drive command at least that often to keep driving.
Robots driven by a remote control should use a shorter timeout, and 0 disables the switch, e.g. on a test bench.
drive_command_age holds the time in milliseconds since the last drive command, whether it was applied or not, for rules that need finer control.
See Machine Safety for the background.
Analog Unit¶
The AnalogUnit module owns an ADC oneshot unit and is shared by one or more Analog or TemperatureSensor modules.
This allows multiple analog channels on the same hardware unit to be used safely without conflicts.
| Constructor | Description | Arguments |
|---|---|---|
analog_unit = AnalogUnit(unit) |
ADC unit index (1 or 2) | int |
This module has no properties or methods and is used only as a dependency by other modules.
Analog Input¶
This module is designed for reading analog voltages and converting them to digital values using the ESP32's ADC units. For detailed specifications of the ESP32 ADC modules, including attenuation levels, voltage range mappings, and GPIO-to-channel mapping, check the ESP32 documentation.
| Constructor | Description | Arguments |
|---|---|---|
analog = Analog(unit, pin[, attenuation]) |
Unit, pin and attenuation level (dB) | AnalogUnit module, int, float |
Possible attenuation levels are 0, 2.5, 6, and 12 dB. The default attenuation level is 12 dB.
| Properties | Description | Data type |
|---|---|---|
raw |
raw measurement value (0-4095) | int |
voltage |
voltage (V) | float |
Temperature Sensor¶
This module reads two analog inputs on the same ADC unit to compute temperature from an NTC divider and a matching reference divider.
| Constructor | Description | Arguments |
|---|---|---|
temp = TemperatureSensor(unit, temp_pin, ref_pin[, attenuation]) |
Unit, GPIO pins and attenuation (dB) | AnalogUnit module, 2x int, float |
The attenuation level defaults to 12 dB.
| Properties | Description | Data type |
|---|---|---|
raw_temp |
Raw ADC reading (NTC pin) | int |
raw_ref |
Raw ADC reading (reference pin) | int |
voltage_temp |
Voltage at NTC pin (V) | float |
voltage_ref |
Voltage at reference pin (V) | float |
temperature_c |
Computed temperature (°C) | float |
The computed temperature is calculated based on the following assumptions:
- NTC thermistor TDK/EPCOS B57332V5103F360 (10 kΩ @ 25°C, B25/85 = 3380 K)
- divider 3 kΩ to GND on both pins
- reference top resistor 10 kΩ to 3V3
Expander¶
The expander module allows communication with another microcontroller connected via serial.
| Constructor | Description | Arguments |
|---|---|---|
expander = Expander(serial[, boot, enable]) |
Serial module and boot/enable pins | Serial module, 2x int |
| Methods | Description | Arguments |
|---|---|---|
expander.run(command) |
Run any command on the other microcontroller |
string |
expander.disconnect() |
Disconnect serial connection and pins | |
expander.flash([force]) |
Flash other microcontroller with own binary data | bool |
expander.restart() |
Restart other microcontroller |
The flash() method requires the boot and enable pins to be defined.
The optional force argument skips the default check whether certain strapping pins are set correctly.
Flashing erases the other microcontroller's NVS:
its startup script, a persisted console baud rate and the bus backup are reset to defaults.
The other microcontroller then boots the copied app from its first OTA slot.
The disconnect() method might be useful to access the other microcontroller on UART0 via USB while still being physically connected to the main microcontroller.
After disconnect() the expander stays disconnected until flash(true) reinstalls the serial connection;
run(), restart() and forwarded calls fail with an error until then because there is no serial connection,
and flash() without force fails because the strapping pins cannot be checked without it.
Both disconnect() and flash() fail if another module, e.g. a serial bus, uses the same serial module.
After disconnect(), the UART and its pins stay reserved for the expander's serial module until the core restarts (see Serial interface).
Proxy modules are set up on the other microcontroller only once, when they are created.
After restart(), flash() or a reboot of the other microcontroller (recognized by its Ready. line), is_ready returns to true, but the proxies no longer exist there:
their is_ready turns false and the main microcontroller needs a restart, e.g. core.restart(), to create them again.
Note that the expander forwards all other method calls to the remote core module, e.g. expander.info().
| Properties | Description | Data type |
|---|---|---|
boot_timeout |
Time to wait for other microcontroller to boot (s) | float |
ping_interval |
Time between pings (s) | float |
ping_timeout |
Time before timing out (s) | float |
is_ready |
Whether the remote module has booted and is ready | bool |
last_message_age |
Time since last message from other microcontroller (ms) | int |
Proxy¶
-- This module is mainly for internal use with the expander module. --
Proxy modules serve as handles for remote modules running on another microcontroller.
Declaring a module x = Proxy() will allow formulating rules like when x.level == 0 then ....
It will receive property values from a remote module with the same name x, e.g. an input signal level.
Note that the remote module has to have turned on broadcasting: x.broadcast().
| Constructor |
|---|
module = Proxy() |
Note that the proxy module forwards all method calls to the remote module.
Proxies cannot be passed as arguments to other module constructors (e.g. as end stops for a motor axis), because the actual module only exists on the remote microcontroller. Declare the depending module on the same microcontroller instead.
| Properties | Description | Data type |
|---|---|---|
is_ready |
Whether the definition was sent in the expander's current boot | bool |
is_ready turns false again when the other microcontroller restarts or the connection is lost,
because the main microcontroller cannot tell whether the remote module still exists (see Expander).
A proxy accepts property declarations without nesting, e.g. float x.level = 0.5, so rules can use a property before the remote module broadcasts it.
An unknown property is added, a known one of the same type is set to the declared value, and a known one of another type is an error.
Nothing is sent to the remote module; its broadcasts overwrite the declared values.