Tuesday, 31 March 2015


Being on shifts has its drawbacks. Stupidly early starts and twelve hour days aren't everyone's cup of tea, and understandably so. But they do have some advantages, and one of those advantages is quite a lot of time off. Four days in every eight in my case.

So I spend my free days playing videogames, watching movies, playing with my dog, or just generally chilling out. And messing about with Raspberry Pi projects of course. Everyone needs a hobby, right?

In my last blog I'd actually built an RPi powered vehicle. I called it G-Bot. It didn't actually do anything, but it looked pretty cool - I thought so anyway. So now the time has come to write some test code and see if I can get this thing to work.

 G-Bot. Click to enlarge (the photo, not the bot...)

I used some of my existing code just to see if the thing would actually move, and the first thing I found out was that I was right to be worried about the weight of the battery. The bot did indeed move, or try to, but I could hear the stepper motors struggling to shift the mass. It was a combination of a tiny growling sound coming from the motors, and lots of (slow) wheelspin from the "tyres". These are really cheap motors and I wouldn't expect them to take much stick, so first thing on the agenda was to swap out the battery for a lighter power source.

Not having a micro-nuclear reactor to hand, I settled for a couple of AA battery holders from the local Maplins. These take 4 x 1.5 volt batteries each, therefor each pack gives an output of 6 volts. While this in theory would be enough to run the G-Bot, I doubled up to two battery packs because they had nowhere near the amount of Amps available that the larger lead-acid battery had. 12 Volts wasn't a problem because the voltage regulator I'm using allows a very broad input voltage range, as long as it's DC, and still gives 5V at the output.

The AA packs combined are less than half the weight of the LA battery.

So with it's new power plant installed, the bot doesn't look quite as neat, but is a lot lighter. I've only bodged the batteries in place temporarily, this is just for a test. Honestly. The battery packs are wired in series, and yes that is electrical tape wrapped around the joint. I'll do a better job once I know this works.

More cargo space available now...

Back to movement testing then! I modified some original code to do a simple straight line test. It basically runs both motors for a time, waits for a second, then runs them in reverse. I also had to reverse the pinout assignment within the code, because the motors are back-to-back now, effectively reversing the rotational direction of one of them in relation to the other. Here's the straight line test code...

Notice the reversed GPIO pin assignments at Line 9

And here's the resulting movement. YES! It moves! I am happy :)

My first ever robot trial. Next stop, global domination.

Inspired by the successful trial, I modified the code to make G-Bot rotate around it's central axis...

The modification is barely noticeable

This block of code is practically identical to the first one, except that I have put the GPIO pinout assignments back in their original order. As the motors are now mounted facing opposite directions to each other, they effectively run in opposite directions. Here's the result...

Hmm, not a full circle...

From this test, I concluded that four full revolutions of the motor wouldn't result in a 360 degree rotation of the bot. This is due to the diameter of the "tyre" in relation to it's distance from the central point of G-Bot and effect of the opposite wheel turning. Uh-oh, I sense maths are gonna be needed at some point. Not my strong point. I'd rather do some trials for now, and work out the formulas later, or ask someone clever to do it for me :)

Anyway, through trial and error, I found out that the motors need 530 signal pulses to make the bot turn 90 degrees. (Remember 512 pulses makes the wheel do one complete revolution - it's all to do with ratios and crap, it baffles me if I'm honest. But I've promised myself I'll found out about this stuff). I modified the original "quarter turns" program and this is the result...

Not perfect, but close enough for testing

Well that went pretty well I thought. The bot does have a little bit of wheelspin still, but I think I need to shave a little off the skids. That should allow the tyres to have more purchase on the ground. Too much though and G-Bot will be tilting about all over the place.

It's important to remember that while I am sending the start commands from my PC, the code that is actually running the bot is sitting on a MicroSD card in the RPi itself. It's all self-contained on board. In theory anything that can run an SSH client could connect to the bot over WiFi and issue commands. That's pretty impressive considering this whole thing has cost about £40 all-in.

So I'm going to sign off with a video of G-Bot attempting to drive in a square, and land at it's original starting position. Until next time, I bid you farewell.

Sunday, 29 March 2015

The Build

After working out how to control a couple of stepper motors independently, the next logical step in my experiment was to build some sort of vehicle. I had a few ideas floating around, but they were either too silly (dual-motor toothbrush bot) or too optimistic (T-1000 Terminator).

You might have to google "toothbrush bot"...

Anyway, I had plenty of bits lying around, so I eventually made a start. I'll warn you now, don't expect anything too impressive - this was my first attempt at anything like this :)

So, I took an old electrical panel cover, drilled a few holes in it and mounted a stepper motor either side. I had a couple of vacuum suckers left over from a previous work project, and I thought they might work as wheels, so after drilling out some bolts to act as axles, I mounted them to the motors. I then glued a couple of rounded nuts to the bottom of the tray to act as skids. It wasn't much, but it was a start.

As usual, click any image for a larger version.

It's upside down here...

Next step was to find a power source. The Raspberry Pi requires 5 volts, as do the stepper motors, but the more common battery voltages are 1.5V (or multiples of it), 6V or 12V. I had a 6 Volt 4 Ah battery in my drawer, but it was (a)quite heavy and (b)the wrong voltage. The voltage wasn't really an issue; simple voltage regulators are quite cheap (I picked one up from eBay for about £3) but the weight was a bit of a concern. I decided to build the vehicle around this power source, with a view to swapping it out later to a lighter one.

The next couple of pictures show me testing the battery, then testing the output voltage after passing the supply through a regulator. This particular regulator will accept 6V - 42V and give a steady output of 5V at 3A (3 Amps should be more than enough to power an RPi, a WiFi dongle and a couple of small motors). [He said, hopefully.]

6.368 Volts direct from the battery, 4.988 Volts through the regulator.

Notice also that the voltage regulator has a USB output. This wasn't ideal for this particular project (you'll find out why later in this post) but it was so cheap it was worth the extra hassle.

OK, so that's our power supply sorted, although I am still worried about the weight. Anyway, I used some self-adhesive plastic mini-trunking (that was all I had available) to stop the battery from slipping around in the tray.

Does it look like a robot yet?

I then mounted a small switch (stolen from a combi-boiler I recently had ripped out) which would act as a main power isolator. I didn't fancy the idea of pulling the connectors off the battery every time I wanted to power down. This switch just breaks the positive supply lead to the voltage regulator.

Mini cable ties are cute and awesome :)

Next up were the actual electronics. There wasn't enough space to lay everything out side by side, so after messing about with designs I decided to raise the RPi above the stepper driver boards. Aside from space saving, this also gives access to the USB ports, one of which will be used for the WiFi dongle. It also allows removal of the MicroSD card from the Rpi, should I bugger something up. Which is likely.

Stepper motor driver boards installed

The RPi itself is raised on pillars, although it doesn't look like it in this photo. The pillars are made from those little nuts either side of a VGA connector that always seem to unscrew themselves. Little bastards.

Totally wonky, but solidly mounted

OK, that was all the essential hardware in place, now for the wiring. I connected the stepper motor flying leads to the driver boards and tucked the wiring in place. Then I attached the power leads to the driver boards, and stripped the other ends. Unlike previous experiments, this time I'm not powering the stepper motors from the RPi itself, I'm powering them directly from the voltage regulator. This means there will be a lot less load on that all-important surface mounted fuse. All I intend to power from the RPi itself (at the moment) is the WiFi dongle. Finally, I connected some jumper leads to the driver boards and it looked something like this...

It's getting crowded already

It was time to wire up the power leads. To do this, I cut a USB lead in half and stripped the cables. We only need to use two of the four cores (Red and Black, the other two are for data - which we aren't using here). I plugged the large USB plug into the voltage regulator output, and ran the stripped ends into a small terminal block. I stripped the other end of the USB lead, connected those to the terminal block and plugged the small USB plug into the RPi. Why bother cutting the USB lead I hear you ask? Well, we still need power for the stepper motor driver boards. So the two jumper leads I stripped earlier also went into the terminal block. I then connected the data jumpers from the drivers boards to the RPi GPIO pins.

This is getting busy!

Almost there...

Finally, I tidied up the wiring and added the WiFi dongle to a USB port...

Well it's compact...ish

The next step will be configuration and testing, but that's for the next blog post. For now, I'll sign off with more pictures of G-Bot. Yes, I named it G-Bot. My gamer friends will know why :)

Did I mention that I'm worried about the weight of that battery?...

Saturday, 21 March 2015


In my last blog, I set myself 3 challenges..

  Get a stepper motor to run in reverse
  Demonstrate precision control of the armature position
  Get two motors running independently, from a single RPi

I did a bit of googling and found that the motors I am using draw a maximum of 92mA under full load, and that includes power used by the driver board. The theoretical maximum current draw for two motors running concurrently is therefor 184mA. Given that the RPi has a safety fuse rated at 750mA, this leaves just over half an Amp to run the RPi itself. I don't want to push my luck, so for the dual-motor experiment I'm going to use an Ethernet connection rather than WiFi (the WiFi dongle is USB powered which means more load on the fuse).

Anyway, on to challenge 1...

Get a stepper motor running in reverse

While this sounds an easy thing to do, it's not quite that straightforward when dealing with arrays, especially multi-dimensional ones. After a few tries (and fails), I worked out the simplest way of doing this is by having two separate control lists, one for forward and one for reverse. We then just run the forward control list for an amount of time, then switch to the reverse control list, then back again etc...

Here's the modified control program which now allows forward and reverse control.

click to enlarge

You can see the two lists, the second one just being a reverse of the first. It is actually possible (and more efficient) to have a single list and have the control pointer run backwards, but for the sake of simplicity, I went with two lists. However, we might need advanced control of a list position pointer for the third challenge, which is something I look forward to taking on*.
[*Not really, it's giving me cold sweats thinking about it]

You might have noticed the number 512 there in those loops. There's a reason I used that particular number and it's explained in the next section, but for now here's a video of the forward/reverse control in action...

Forward and reverse motion


Precise control of armature position

Probably the best way of demonstrating this is to have the motor stopping and starting at specific points, something a normal AC or DC motor simply couldn't do. Well it could if you used a power control inverter and some method of obtaining the shaft rotational position (a pulse counter or high resolution tachometer or something), but even then it it's not hugely accurate.

First, I did a little research to find out exactly how many steps were used to make the output shaft of our stepper motor rotate a full 360 degrees. I should mention here that the shaft sticking out of the motor unit isn't the armature. That would give a pretty awesome rotational speed, but wouldn't have enough torque to be of any use. The units are geared down internally in order to give us usable rotational power, but at the expense of speed. It turns out that 512 complete turns of the armature results in 1 single turn of the output shaft with a speed variation ratio of 1:64. That basically means the output shaft is spinning 64 times slower than the actual armature.

So now we know that if we send 512 sequential steps to the motor, the output shaft will rotate once. (Remember the number 512 from the control loops in the earlier section? That's why I used that particular number.) Breaking this down, we could send it 256 steps to make it do half a turn. It follows that sending it 128 steps will make it do a quarter of a turn - or 90 degrees. I think you get the idea.

So I modified our basic Python program to do a few things differently. Firstly, it's now looking out for when I manually stop the program running, and if I do, it "cleans up" the GPIO pins before quitting. This just means it sets all the pins to a logical low state, it's a good habit to get in to. Secondly, instead or running through a never-ending loop, the controlling part of the program actually counts up to 128 (remember 128 steps equates to a 90 degree turn of the motor output shaft). Finally, there is a delay statement which makes the program sit idle for a second before running the count to 128 again.

Quarter turn program - click to enlarge

The result of these changes can be seen in the video below. The motor shaft turns 90 degrees, waits a second, turns another 90 degrees etc... and carries on until I stop it manually. Try getting that kind of positional control out of a normal motor. Not gonna happen easily.

Quarter-turn steps


Two stepper motors running independently, controlled by a single Raspberry Pi

OK, here's where things get tricky. I'll admit, I had a pretty decent idea of how to complete the first two challenges even before I started them, for this one I'm winging it.

Before we start, here's a drawing of how the dual driver boards are physically wired to the RPi.
GPIO wiring - click to enlarge

Each driver board is supplied power from the 5V rail (and Ground) of the RPi. I simply used an additional four GPIO pins to control the second motor. Before we get into independent motor control, we need to test the RPi can actually drive two motors, so here's the code to do that...

 Dual motors - click to enlarge

You can see that I've assigned a second set of GPIO pins as outputs, and initialised them. Later in the program, in the control loops, I've just added an extra line so the control signals are sent to the second motor as well as the first. That's the absolute simplest way to test if something works or not, send it known good control signals, and see if it mirrors the first device.

So even though that modified code will run two separate motors, they aren't being controlled independently, they are basically just receiving the exact same signals, and will do exactly the same thing. There is no way to tell one motor to do something, without the second motor doing exactly the same. Anyway, at least it worked, and here's the video to prove it...

Please ignore my water bill in the background...

So now we know the hardware is physically capable of driving two motors, and those motors are controlled from two separate sets of GPIO pins, it's "just" a case of writing some Python code to allow them to be individually controlled. Here goes...

Code to control 2 motors independently

Well, after a bit of head scratching and some trial and error, some code finally emerged that allows the two motors to run independently of each other. I decided early in the process that it's a lot simpler to stick with separate sequence lists for forward and reverse rather than having a bidirectional program pointer. I know that time is coming, it's just not yet. I've commented the code itself, so I won't go into detail about what each line does, but this is the general idea...

The RPi picks two random numbers for each motor. The first of these numbers will define how many steps the motor will take. Remembering that with these particular motors 512 steps equals one complete revolution of the output shaft, I limited the number to be no more than 256. This is purely for demonstration purposes, so we have to wait less time before a potential direction change. Which brings me on to the second random number. This can only be one of two possible values, and it decides which direction the motor will run in. Basically, there is an "if" statement in the motor control loop that can take one of two paths, depending on which number was chosen.

I'd like to thank my friend David Somers for explaining to me how the random number generator works in Python :)

Finally, a (very dodgy quality) video of the motors running.


As you can see, they run for a random time in a random direction. I apologise if you can hear my daughter laughing in the background, she's recently discovered the wonders of red wine.

So, now I know the RPi is capable of running two motors, and I am capable of writing code to control them independently of each other. Whatever next, a robot?..