Tag Archives: pi3hat

pi3hat python raw CAN-FD

The pi3hat, among other things has 5 CAN-FD ports. You can use them to drive a lot of moteus servos, but they are perfectly fine CAN-FD ports generally. The C++ library has always been able to send and receive arbitrary frames (and recently at arbitrary bitrates), but the python interface was lacking, only exposing a portion of this functionality.

As of version 0.3.11, the python library (pip3 install moteus-pi3hat) now exposes everything you need to be able to send and receive arbitrary CAN frames from any of the ports, as well as configure all the timing options for waiting for responses from slave devices.

This is what a sample usage of raw frames, mixed in with moteus frames, looks like:

# To send a raw CAN, you must manually instantiate a
# 'moteus.Command' and fill in its fields, along with which
# bus to send it on.
raw_message = moteus.Command()
raw_message.raw = True
raw_message.arbitration_id = 0x0405
raw_message.bus = 5
raw_message.data = b'1234'
raw_message.reply_required = False

# A single 'transport.cycle' call's message list can contain a
# mix of "raw" frames and those generated from
# 'moteus.Controller'.
#
# If you want to listen on a CAN bus without having sent a
# command with 'reply_required' set, you can use the
# 'force_can_check' optional parameter.  It is a 1-indexed
# bitfield listing which additional CAN buses should be
# listened to.

results = await transport.cycle([
       raw_message,
       controller.make_query(),
   ], force_can_check = (1 << 5))

# If any raw CAN frames are present, the result list will be a
# mix of moteus.Result elements and can.Message elements.
# They each have the 'bus', 'arbitration_id', and 'data'
# fields.
#
# moteus.Result elements additionally have an 'id' field which
# is the moteus servo ID and a 'values' field which reports
# the decoded response.
for result in results:
    if hasattr(result, 'id'):
        # This is a moteus structure.
        print(f"{time.time():.3f} MOTEUS {result}")
    else:
        # This is a raw structure.
        print(f"{time.time():.3f} BUS {result.bus}  " +
              f"ID {result.arbitration_id:x}  DATA {result.data.hex()}")

It isn’t the cleanest API, but it does get the job done!

pi3hat configurable CAN

To date, the pi3hat CAN channels only supported CAN properties suitable for use with moteus controllers. Given that’s what most people are using them for, that’s fine. However, there was no real constraint behind that, just laziness.

Thus, I’ve released new firmware for the pi3hat that supports configuring the bitrate, FD-ness, and other properties of all 5 CAN channels.

Currently only the C++ library exposes the configuration functionality, but it will be easy enough to add to python when someone needs it.

pi3hat r4.4

It seems like all the posts I’m writing these days are for new products! Here’s the pi3hat r4.4:

There are two changes from the previous r4.2. First, it now supports voltage inputs up to 44V. Second, in support of future upgrades, the 5th CAN-FD port has been upgraded to support 8Mbps, but downgraded to no longer have a wide common mode voltage range.

THUS, IT IS NOT SAFE TO CONNECT THE CAN-FD PORT ON THE pi3hat r4.4 TO A power_dist r3.X BOARD.

Also, it is in stock at mjbots.com!

That said, the worldwide electronic supply chain is still in shambles. That combined with the Chinese New Year means that stock may be intermittent, and slight alternate versions to adjust to different parts may be forthcoming.

New cross-platform moteus tools!

After receiving many requests via youtube, discord, and email, I’ve finally gone ahead, bitten the bullet, and updated all of the moteus tools to be pure python and work in a cross platform manner. Now, the only thing you need to do to install pre-compiled versions of tview and moteus tool on most* platforms is:

pip3 install moteus_gui
python3 -m moteus_gui.tview    # (or maybe just tview)
python3 -m moteus.moteus_tool  # (or maybe just moteus_tool)

I’ve personally tested these on Linux, Windows, and Raspberry Pi, and others have at least verified basic operation on Macs. Python 3.7 or greater is required.

….

But wait, there’s more!

Now, both moteus_tool, tview, and the python bindings more generally can use python-can as a transport. That means tview can now be used with socketcan, pcan, and a bunch of other options. To one up that, most users won’t have to even specify any command line options, as tview and moteus tool will automatically select a fdcanusb or python-can depending upon what is available.

I’ll be updating the devkit introduction video soon, although the commands in there will largely continue working for the time being.

Errata

  • Neither pypi or piwheels has pyside2 for the Raspberry Pi, but it is packaged in Raspberry Pi OS. You can follow the instructions in git to find a recipe that works.
  • To use the pi3hat, you need to also do pip3 install moteus_pi3hat

moteus and socketcan

Various users have been trying to use lower-cost Raspberry Pi CAN-FD adapters for the moteus controller for some time (like this one from Seeed), but have had problems getting communication to work. I buckled down and went to debug the problem, discovering that the root of the issue was that the linux kernel socketcan subsystem calculates very sub-optimal CAN timings for the 5Mbps bitrate that moteus uses. This results in the adapters being unable to receive frames sent at the actual 5Mbps rate, but instead only slightly slower.

The solution is to manually specify the bus timings when configuring the socketcan link. This makes the MCP2518FD boards work, and also PEAK-CAN-FD USB adapters (and probably every other socketcan CAN-FD adapter) work as well. You can find the timings linked in the moteus reference documentation: https://github.com/mjbots/moteus/blob/main/docs/reference.md#bit-timings

General socketcan improvements

As a result of all this debugging, I made some general improvements to socketcan support in all the client side moteus tools.

  1. There is now a documented commandline for invoking moteus_tool from socketcan: https://github.com/mjbots/moteus/blob/main/docs/reference.md#moteus_tool-configuration
  2. I released moteus and moteus_pi3hat 0.2.0 to pypi. These provide socketcan interfaces for python, transparently using them if no fdcanusb or pi3hat peripherals are found.

Thanks for everyone on discord’s patience as we worked through these compatibility issues!

Automated wire stripper and cutter

Over the Thanksgiving day holiday, I knew I had a bunch of harnesses to build. Rather than being a good corporate steward and actually building them, I instead built a machine to automate the first of the 3 time consuming parts of the harness construction: wire cutting and stripping.

This was just thrown together from two cosmetically damaged moteus devkits, a Raspberry Pi 3 an old development version of a pi3hat, a hand wire stripper, two synthetic rubber bands, an off the shelf 24V supply, and a bunch of 3d printed parts.

Why?

Simple automated wire management at the DIY level is not new. It’s been done many, many, many times before. YouTube has decided that every day I need to see someone else’s take on the problem. Look down in the resources at the bottom for my collection of alternate solutions.

What differentiates this version is (1) I built it most from junk parts I had around, (2) since it uses brushless motors it can be both very fast and very precise. Here’s a clip of it executing a few cycles where it strips 3mm from the front end, pre-cuts 3mm from the other end, then cuts the wire to a total length of 5cm. The overall cycle time for all operations is around 1s per wire for the 30cm wires I needed right now.

By replacing the guides and doing some tuning, it should be capable of managing wire between 30 AWG and 18 AWG, although to date I’ve only tested it on 26 AWG.

It did take a bit longer than the weekend — I printed a second revision of everything early the following week, then waited for a panel mount switch to make the power supply look more professional.

Video

Here’s the overview video, with some more shots of it in operation.

Resources

The BOM, .3mf’s and source code are in github at https://github.com/jpieper/bstrip. There is a hackaday page here for discussion: https://hackaday.io/project/176211-bstrip-wire-cutstrip

Maybe someone else will find it useful?

Other DIY-style solutions

pip3 install moteus

I’m excited to announce new python bindings for communicating with moteus controllers! A simple example from the README:

import asyncio
import math
import moteus

async def main():
  c = moteus.Controller()
  print(await c.set_position(position=math.nan, query=True))
  await asyncio.sleep(1.0)

asyncio.run(main())

This code will try to locate an fdcanusb on your host and use it to communicate with controller with ID 1. All of those details can be customized through code depending upon how you construct things. The library is pure python, although it doesn’t work on Windows currently because it relies on an asyncio aware pyserial wrapper that doesn’t work there.

At the same time, there is a parallel python library “moteus-pi3hat” which only has an armv7l package. This provides an identical API for working with the pi3hat on a Raspberry Pi. It lets you configure which controllers are attached to which bus (by default it assumes everything is on bus #1). After setting that up you can use an identical API to command and monitor the controllers.

Thanks to everyone in discord who helped test!

Measuring the pi3hat r4.2 performance

Last time I covered the new software library that I wrote to help use all the features of the pi3hat, in an efficient manner. This time, I’ll cover how I measured the performance of the result, and talk about how it can be integrated into a robotic control system.

pi3hat r4.2 available at mjbots.com

Test Setup

To check out the timing, I wired up a pi3hat into the quad A1 and used the oscilloscope to probe one of the SPI clocks and CAN bus 1 and 3.

Then, I could use pi3hat_tool incantations to experiment with different bus utilization strategies and get to one with the best performance. The sequence that I settled on was:

  1. Write all outgoing CAN messages, using a round-robin strategy between CAN buses. The SPI bus rate of 10Mhz is faster than the 5Mbps maximum CAN-FD rate, so this gets each bus transmitting its first packet as soon as possible, then queues up the remainder.
  2. Read the IMU. During this phase, any replies over CAN are being enqueued on the individual STM32 processors.
  3. Optionally read CAN replies. If any outgoing packets were marked as expecting a reply, that bus is expected to receive the appropriate number of responses. Additionally, a bus can be requested to “get anything in the queue”.

With this approach, a full command and query of the comprehensive state of 12 qdd100 servos, and reading the IMU takes around 740us. If you perform that on one thread while performing robot control on others, it allows you to achieve a 1kHz update rate.

CAN1 SPI clock on bottom, CAN1 and CAN3 bus on top

These results were with the Raspberry Pi 3b+. On a Raspberry Pi 4, they seem to be about 5% better, mostly because the Pi 4’s faster CPU is able to execute the register twiddling a little faster, which reduces dead time on the SPI bus.