Science Hack Day pt. 2: The stepper motor

My first post about Science Hack Day covered the fits and starts of working on the hackathon day and covers why the raspberry Pi turned out to be way less than ideal. This post is drawn from the last part of the hackathon, when we were driving the stepper, and what I learned about accuracy, and timing, in that experimentation

caveat: I am 100% not a mechanical engineer

Dozens of concerns were mentioned to me about the design of this tool, and I found a few others with a little googling, that implied we might have difficulty while trying to ‘drive’ the tool at the right speed with sufficient accuracy. None of these turned out to be actual problems, but I’m so ignorant on the subject I might not even have the right terms as I try to describe them. Sorry!

Okay what does this device even look like?

The process we’re talking about is stereotactic surgery, where bones are used to lock in a coordinate system for finding an exact point in soft tissue. The term could refer to any kind of surgical procedure, but usually we’re talking about the brain, since the skull is such a convenient ‘hard point’ to start your coordinate system.

To perform surgeries like this, they use a tool like this one:

The instrument. Image taken from lab supply company http://www.stoeltingco.com/
The instrument. Image taken from lab supply company http://www.stoeltingco.com/

The part of this that really matters are the two ‘knobs’ you see at the top left. The scientist twists these to move the probe. If you’ve ever worked with a 3d printer, this probably looks familiar. You’re looking at a hand-cranked 3d control system.

The upgraded version of this tool looks like this:

There are a lot of ways to 'computerize' this tool, but I chose this one since the conversion is more obvious. ibid
There are a lot of ways to ‘computerize’ this tool, but I chose this one since the conversion is more obvious. ibid

This version should look very familiar to someone who has worked with either a 3d printer or a CNC: the hand cranks are now motors, and a controller for those motors is hooked up to PC control.

The paper that Daniela found was about building a full 3d tool with open source hardware at a significant cost saving. She would find such a tool useful someday, but for the moment she just wanted one that moved on the Z-axis automatically, with manual controls for the X and Y.

So this whole goal is to build something that uses a stepper motor to turn a single knob.

Again, I had the advantage of a machinists’ work before the hack day to build the mechanical connection between motor and tool.

My concerns about the motor

  • Accuracy
    The probe needs to move ‘in’ by a total of 2mm over the course of a minute. Since we’re doing this in a surgery, it’s prooooooobably not good to end up moving 2.1mm. The ‘stepper’ part of stepper motor means it moves forward in discrete steps. My big fear was that the right distance would be between steps. If the system moved 3mm in 17 steps, there wouldn’t be a right number of steps to go exactly 2mm. Thankfully, since we were using a ‘geared’ stepper motor that steps down the speed of turning with a gearbox, this wasn’t a problem. A full rotation of the motor took a few thousand steps. Plenty of resolution.

  • Smoothness
    Again taking the example where the stepper moves the whole length over a dozen or so steps, this motion might look smooth to the naked eye, but microscopically they’d look like separate thrusts, which might not look good. Again, the resolution of steps resolved this.

  • Calibration
    I knew there were ways to look at the machines involved and calculate the expected distance of movement but 1) I didn’t know how to do that and 2) it sounded hard so I came up with the clever idea of just making the tool move, measuring the distance, and ‘calibrating’ to find the right number of steps to go 2 mm. At first I thought it would be tough to measure these tiny distances, but the version of the tool that Daniela brought had little dial readout of the distance of movement. In the end this was super easy!

  • Speed and sync
    The stepper driver in use probably had a spec available somewhere of the maximum rate it could accept instructions. The controller (raspberry Pi and/or Arduino) also have a maximum accuracy with which they can send signals out. One request from Daniela was that the probe move faster coming back out than it did going in, and I was worried that this higher speed might end up with signals ‘lost’. If you send ‘step’ signals faster than the motor can actually get them, you could miss steps and end up not moving the full distance.

I tested this extensively by throwing a ton of steps at the system at speeds much higher than required. Even with the Pi, which should have much more difficulty sending signals at high frequency, had no trouble. This wasn’t that surprising, after all we were going super slowly.

  • heat
    Stepper motors eat up a lot of current. Both the motors themselves and the stepper driver get really hot
See that big metal bit toward the type? It's a rather large heatsink to dissipate the heat. Image from tronixstuff.com
See that big metal bit toward the top? It’s a rather large heatsink to keep this part cool. Image from tronixstuff.com

Where a lot of the other problems I came up with were obviated by the slow speed and high number of steps, energy usage and concomitant heat buildup are actually worse for a more accurate tool.

Stepper motors can accept a big range of voltage. The more voltage, the stronger the grip of their magnets and the more accurate each step would be. That meant we ran our stepper at its max allowed voltage. We actually killed two of the tiny ‘cute’ stepper motor drivers in our testing.

We ended up using a version of the driver above with a huge heatsink. The motor itself also got pretty hot hot. Similar rigs to do 3d printing have cooling fans mounted on the frame to cool the motor itself. But I calculated that on the hack day we moved the probe more distance, at a higher speed, than it would move over a year of use. The system didn’t melt, we were okay.

stuff other people mentioned

  • free-wheeling
    If you turn off all current to the coils of a stepper motor, it should allow the wheel to turn freely. This would be super duper bad if the surgical probe just started moving around during a procedure. Normally this is handled by the hardware/software driving the stepper motor: giving it no instructions actually leaves one coil on holding the motor. I started to do a bunch of checks on this before I tried just turning off the power to my motor entirely. It turned out that the gearbox and the probe hardware presented way too much resistance for the thing to move on its own

  • reversing
    I’m not going to go to deep on this, but when you try to move back the way you came, there’s some ‘slack’ in the gears that needs to be taken up, losing you some steps. This difference proved too small to measure, and the probe gets ‘zeroed’ before every procedure anyway, so a problem can’t build up over a bunch of procedures.

  • timing from the Pi
    See my previous post: the Raspberry Pi was totally capable of running the driver.

what we learned

Optimization of a system, whether that system is electical, mechanical, or software, is only really meaningful after you have a working prototype. Problems like heat on the stepper motor driver are easily predicted and are worth handling early. Other problems should come up in trial runs, and if not, any time spent preventing them was largely wasted.

So build, and test! When you test, test a lot of stuff. Try your best to simulate uses more extreme than the real world should throw at them, and document what you find and notice.

the next and final post about science hack day will cover the control software I wrote for the arduino, and why an open-source stereotactic surgical might not be that great an idea.

Science Hack Day!!! -or- The Raspberry Pi, Stepper Motors, and Man’s Folly

Science hack day Portland was, without a doubt, my favorite hackathon event I’ve ever attended. So many things to love about it:

  • Slack channel invite a few days before to get on the same page/find teams
  • lots of real scientists attending, some bringing real problems
  • generous spread of hardware
  • not organized 100% by dudes
  • food was amazing

The Plan

I signed up thinking I might make some simple electronic whatnot or maybe some kind of ‘science-related’ complete project. Like a… weather station? Those are still a thing, right? Thanks to the slack channel set up beforehand, I found a scientist who was trying to get a real piece of lab equipment made, and even had an open-source project that they were basing their project on. So I’d be making a tool to carefully manipulate a probe. As it pushes into… an animal’s brain.

Science hack day had officially gotten real.

The version that Daniela Saderi wanted for her lab wasn’t going to grind bone like the open-source original, it was just going to handle a probe, moving only on one axis. The good news was that she already had an Electrical Engineer and Machinist on the project, otherwise the coupling between the probe and the stepper motor would have taken me the whole weekend.

So she was bringing all the necessary parts, and a stepper motor connected to a probe manipulator, all I needed to do was design some software to control the thing.

The Huge Mistake

I decided to try and control the system with a Raspberry Pi. This was a huge mistake for reasons I’ll get into, but I picked it for what seemed like good reasons:

  1. Mozilla had generously donated 35 of the buggers to the event.
  2. the user (Daniela) wanted a lot of customization on the tool. Adjustable speed, depth, pausing and restarting, all needed to be controllable.

The question I got asked throughout was ‘why not use the Arduino?’ And I did my usual scoff at this kind of question: there’s always a better tool out there, just let me use what I have dammit!

But really, motivation was the complexity of the interface Daniela wanted. I knew that displays and button inputs existed for the Arduino, but I didn’t really know much about them, I didn’t have the hardware necessarily, and I felt like the programming would be more complex.

Prompting the user to enter a speed and depth on a command line interface is easy for me, but making some little LCD display data and handling button input both sounded… hard.

Arduino and Raspberry Pi side by side
The Raspberry Pi is a complete PC (below) next to an Arduino (above) which, while programmable, isn’t much smarter than the electronics in your microwave’s keypad.

Oh and also: while Johnny-Five lets you write in Javascript for the Arduino it doesn’t actually… work the way you think it does: it requires the Arduino be hooked to the PC. To write code that just runs on the Arduino, you gotta write C.

I’m not that terrified of swapping programming languages? But it just seemed fun to be able to get the thing working in Javascript! And Johnny-Five can run directly on the Raspberry Pi (of course it can, it’s a PC!). I even plugged Johnny-five on the Pi to a few people in Slack in the days leading up to the event.

Why that was a mistake

a PC is a PC

In the end, I never got Johnny-Five to work on the Pi, and ended up having to write the Raspberry Pi controls in Python. I’d never written any Python, so that wasn’t super.

Also the thing about using a super-compact computer to be your computer is it just took so much time getting that fukkin’ PC to work. I was all excited about a tutorial that would let me get the Pi on WiFi and let me SSH over to it, but one of the steps was to update the OS. Of course, the OS update took half an hour, and with other little problems with hardware and video it was noon before I was even really working on my Pi.

Compared to setting up a full-blown new PC 3 hours isn’t terrible but it really shows why people prefer making simple projects on the Arduino.

just one letter separates ‘networking’ from ‘not working’

One thing that REALLY bit me: I followed a lovely tutorial on getting the Pi set up for SSH and Johnny-Five development, and the last few steps did not work right. First, I couldn’t get Mongo to serve the Pi at a hostname, and wrestled with that for a while.

After that, I couldn’t get the fileshare set up with the method they described, and ended up having to use… something else (I’m sorry, I’m sorry, I have no idea what it was and all the results I found were for Samba and smb and that did not work for me)

Once I had that done, I was able to remote into the Pi and write code from there. With the fileshare I could use Atom on my laptop and not be stuck with whatever weird IDE the Pi had. Great right? Not so much.

Since I didn’t get Samba set up right, I was accessing the Pi by its IP address, and this got reassigned by the network once or twice during the event. When this happened my attempts to load new code failed silently, and the sequence I was triggering would fail because it was running code from 10 minutes ago.

When I write code and it doesn’t work, network issues preventing the system from getting the latest version of the code are not my first guess about the cause. As a result this cost me an hour of debugging before I figured out the real problem.

Oh Johnny why you gotta do me like you do

After all that, possibly related: I couldn’t get Johnny-Five to work. I would get a few steps forward and then hit new roadblocks. The final version would run the code and throw me into a REPL. Was that it working? It sent the signals. But by throwing me into the REPL I couldn’t do console logging like I expected. It sent me some error messages that I… couldn’t understand.

johnny-five

Johnny-Five is an awesome project and it has a ton of rad uses. There’s also an “Espruino” hardware platform that takes Javascript direction. There was actually a presentation on this at the hack day that I missed on the Flasher.js sdk to do just this.

But don’t knock the Raspberry Pi

One thing I heard a few times, even read from some people who were writing hardware control software for the Pi, is that the Pi can’t control a stepper motor. This concern turned out to be quite overblown, I’ll explain:

A stepper motor is a wheel of magnets surrounded on four sides by electro magnets. As the magnets around the edge switch off and on, the wheel inside moves forward.

Stepper Motor animation, described in the paragraph above

for precision, they’re the dominant design, since at low speed it’s a bit like rolling a square wheel: you’re never unsure exactly how many times that wheel has turned.

If you’re curious: steppers aren’t the best at everything since they’re very power inefficient. They also require a ton of power to stay still (this wasn’t a problem for me since our motor had a gearbox that required force to move, so our probe wasn’t just wobbling around when the motor was off.)

All of this to say: controlling a stepper motor directly requires you to turn off and on these magnets around the edge. Obviously, the switching has to be really precise to ‘drop’ the wheel from one magnet and ‘catch’ it with the next.

the Raspberry Pi is a cut down PC, and it lacks a bunch of hardware involved with timing.

Here a sidenote: the chips on a normal PC that precisely control timing and allow for multiple tasks to work on in parallel while remaining in sync is called a ‘clock chip’ and is unrelated to telling time. My Father has worked for several decades making this exact part for a large semiconductor company.

Since the Pi can’t sync up its signals perfectly, it can’t handle controlling these magnets.

Okay, but these are really strong magnets, surely we’re not going to run them with power directly from the board, right? At the very least, you’d want a transistor to let a little bit of current from your controller direct a bunch more to the motor.

closeup photo of the pins on an Arduino
The General-Purpose Input/Output or GPIO pins can do a lot, but they can’t power your toaster oven

And here’s where we come to a basic thing with hardware hacking: powering LED’s or getting button input are all things that these controllers can do directly, but for more complex stuff you have a choice!
* design your own fancy circuit
* send simpler signals from your microcontroller to specialized hardware.

These are the famous “shields” for the Arduino. A lot of them aren’t necessarily required to do whatever, but they make it a ton easier to write the software to control whatever.

In this case, there exist stepper motor drivers that take very simple signals instead of requiring you to control each magnetic coil. Set up right, these ‘drivers’ will just take signals on 2 pins: a ‘step’ signal and a ‘direction’ signal, and handle all the fiddly “turn on this magnet, then turn on the next one right away, no, NOW”

By the by, we borrowed a Stepper Motor Driver from… someone… on the day of the event and I haven’t actually found another one that works just like this. I’ll figure it out eventually, but anyway!

Lessons learned

doing too much at once makes debugging a nightmare

At my job, where I’m using a library I’m very familiar with, I still rarely write more than a few lines of code without checking some debug output. Trim a string of a few characters, escape it for HTML, and then send it in a JSON object? I’ll often console.log() both the input and the escaped string before I move on to step 3.

By contrast, at 1pm on the hack day, I was SSH’ed into a Raspberry Pi running a Linux build I’d never used before, with an unfamiliar Javascript Library, to make the Pi control a stepper motor driver, which I’d first heard of the day before.

The first attempts to turn the motor was 27 lines of code. Not even counting the other tools, this was extreme.

After an hour of frustration, I disconnected the Pi from the motor, and went back to basics: trying to make the Pi blink some LED’s

It was doing the easiest possible task that revealed that Johnny-Five wasn’t working correctly, and that Python was.

In the end

The hackathon was a single day. By the end of the day I had the actual probe hardware moving the exact right distance in, pausing, and then moving back out. This wasn’t really a minimum viable product, since it needed to wait on input before going to the next stage. Still pretty cool to know the hardware setup and the Pi could manage such precise control, to move a probe just 2mm in 100 seconds!

If I get to it, I’ll write up how I went from that to the Arduino version in both hardware and software. For now you can check out my code for in Javascript, Python, and C