Saturday, 28 February 2015

Stepping out

Wow!, has it really been more than a year since my last blog post?! Time really does seem to fly! So if I'm honest, I haven't really been doing too many experiments with the RPi. Real life has a habit of getting in the way, as I'm sure everyone is aware. However, I haven't been totally idle.

My original Raspberry Pi (Model B) is now acting as an awesome media centre downstairs on the main TV, streaming 1080p HD movies across my home network via an amazing piece of (free) software called RaspBMC. This is basically a heavily modified version of XBox Media Centre which has been adapted to run on the RPi, and it runs really well (on a Model B Rev 2 at least). The RaspBMC software is about to have a major overhaul to a completely new framework called OSMC which should provide an even more awesome experience, but for now RaspBMC works perfectly.

My Raspberry Pi 2 is currently running something called RetroPie, which is a nifty bit of software that runs in conjunction with the Emulation Station front end to provide a superb little emulator of vintage games. I'm currently running this on a 42" TV using an Xbox 360 controller but I plan to acquire a 3.5" tft and cram it all into an old handheld system, to make a portable games machine that can emulate all the old classics such as ZX Spectrum, Commodore 64, Amiga, SNES, etc.. But that's for a different project (and a different blog post).

So that just leaves the Raspberry Pi Model B+. This is the unit I now use for messing about with. I haven't been doing much lately, so rather that let my hobby fade, I decided to try something new. I'd heard of stepper motors, used them in work in fact, but I had no real idea of how they functioned or were controlled. So off I trotted to eBay and blagged a few small stepper motors for experimentation. They weren't too expensive, so it's not the end of the world if I blow them up. These are the ones I bought, but that link might not last forever, so for reference they are "5V 28BYJ-48 4-Phase Stepper Motor with ULN2003 Driver Board". They were just under £4 each with free delivery.

Stepper motor and driver board

The above picture shows what you get. How they can make something like that, offer free delivery, sell it for £4 and still make a profit is beyond me, but I digress.

Anyway, how to get this thing working? And more importantly, how to get it controlled via the RPi?

After some research (you don't get instructions with the motor) I found that there are a few different types of stepper motor, and also a few different ways of controlling them. For the sake of reference (and to keep this post relatively short) I'm only going to explain how I did it with this particular model.

So the driver board needs a permanent 5V supply. Perfect, we have a 5V rail on the RPi, so we can use that as long as the required current isn't too high. The 5V rail is protected by a 750mA fuse, but that fuse also protects everything else on the board, so we have to be careful not to overload it.

As for actual motor directional control, this is where things get interesting. Unlike a normal motor where you just apply power and off it goes, stepper motors are built with a series of coils that need to be activated in a certain sequence to generate the magnetic field needed in order to turn the armature. (The armature is the actual part that spins). Having control over these individual coils means we can have very accurate control of the angular position of the armature. In fact, we can move it in tiny little steps - hence the term 'Stepper Motor'.

The driver board (the square bit with the microchip on in the above picture) allows us to send a low voltage signal which is in turn used to activate a gate which allows a higher voltage through the chip to energise a coil in the motor. Notice I said coil, not coils. This particular motor has four coils, so we have four inputs on the driver board, one for each coil.

Half-stepping and Full-stepping

Before I go any further, take a quick look at this diagram...


As you can see, there are four coils, each with an input (A, B, C & D) and they all have a common return. These 5 wires are the 5 you can see running from the driver board to the motor in the first picture. The armature in the middle is the part that spins. Without going into the theory of how electric motors work, here is the (very) basic premise of what makes this motor spin...

The armature is a permanent magnet, and as you know, magnets attract each other if the polarity is opposing. Also, when you pass an electric current through a coil which is wrapped around a ferrous bar (or torus, or any shape really) a magnetic field is generated in that medium. So, referring to the above diagram, if we generate a magnetic field in coil 1, then the armature will spin around and align itself with that coil. Then, if we turn the power off coil 1 and energise coil 2, the armature spins around and aligns with that one. I think you get the picture.

Please note that this is a very simple representation of how a stepper motor works. In reality, the armature has a a number of magnetised areas (16 in the case of our motors) which align with "teeth" that are magnetised on the stator (the part that houses the coils), but that's way beyond the scope of this blog. Plus I need a cuppa just now.

Anyway, energising the coils in the correct order causes the armature to spin. Now there is a slight twist on this. (See what I did there?) We can energise the coils in the order A > B > C > D and the motor would indeed work. It does, I've tried it. As you can probably guess, this is called "Full Stepping" and it means the armature "points" to one coil, then the next, then the next etc.. This gives us a reasonable output speed, but not much turning force (Torque). We can get much better torque, at the expense of rotor speed, by using a method called "Half Stepping".

"Half Stepping" is where we energise coil 1, then coils 1 AND 2, then coil 2, then coils 2 AND 3, then coil 3 etc... Basically creating an extra point between coils for the armature to align with. This works because of the way a magnet will align itself mid-way between two identical fields. Physics, or something.

So now obviously we need eight steps instead of four, to make our armature complete a revolution. This won't be a problem as we are going to use the Raspberry Pi to energise the coils in the right order, by means of a Python program controlling our old friends, the GPIO pins. We connect 4 GPIO pins to the 4 inputs on the stepper motor driver board and we're ready to do some coding. Note in the following picture, I've massively over-complicated things by using a piece of breadboard as a junction box. I didn't have any female to female jumper leads, so had to join some female to males. Anyhow, trust me there are only 6 wires between the RPi and the stepper driver; 2 power and 4 control.

As usual, click for a larger image

So onto the code. The easiest (although not only) way to apply power to certain GPIO pins in a specific order is by use of a list. We just scroll through the values of a list, if it's a 0 we turn the GPIO pin (and therefor the motor coil) off, if it's a 1 we turn the GPIO pin (and motor coil) on. When we get to the end of the list, we just jump to the top and start again. This will keep our motor rotating indefinitely. Here's the code...

Click for a larger view
So for those interested, a breakdown of the code..

The #import libraries section just grabs the required libraries to save us having to write code which has already been written by someone a lot cleverer than me. We need the 'time' library because we use a delay to control how fast our motor will run.

The next three sections set up the RPi, telling it we want to use the BCM standard for addressing the GPIO pins, set up a small list to tell our program which physical pins to use in this case, sets them all up for output rather than input, and then sets all their values low.

The #define sequence area of the program is the main coil control list I was talking about. If you look at the columns of 0's and 1's, imagine the leftmost column representing coil A on the motor, the second column represents coil B and so on. If you look carefully, you'll see it's actually a list inside another list. Hmm, hard to explain. The main list (called Seq) has 8 items. Each of those items contains 4 further items which are the 0's and 1's. This is known in most programming languages as a multi-dimensional array, but I might start sounding like I know what I'm on about, so I'll stop there.

Anyway, the #main loop part is, strangely enough, the main loop of the program that actually causes stuff to happen. More on that in a sec.

Finally, the #cleanup when done part just resets all the GPIO's and is good practice when using input/output of any kind on a microcontroller. Having said that, eagle-eyed readers will notice that this part never actually gets executed as the main loop is set to run continuously. The reason for this is because I only wrote this program to demonstrate this single blog post, it will be expanded as time goes on to incorporate more functions etc.

So that main loop eh? Complex? Not really. The "while True" line just means "keep going forever".

Next we run a 'for' loop using a variable called 'halfstep' that counts up from 1 to 8.

Within that loop, we run another 'for' loop using a variable called 'pin' that counts up from 1 to 4.

This next line is the meat and potatoes of it all...

GPIO.output(ControlPin[pin], Seq[halfstep][pin])

...that just basically sets the right GPIO pin to the right value, depending on what point in the loops the program is. Remember 'pin' is counting from 1 up to 4, for each iteration of 'halfstep' which itself is counting from 1 up to 8. Sounds complicated to the uninitiated but nested loops are common practice in any programming language.

The 'time.sleep' line is just used to put a small delay between activating the GPIO pins. If you send the signals too fast, then cheap motors can't react in time and all hell breaks loose.

Here's a short video of it actually running...


...and one of it slowed down so you can see the LED's on the driver board representing the outputs from the RPi GPIO pins. Each LED is connected to one coil on the motor stator. The armature doesn't appear to be spinning at all in this video, but trust me it is. I had to slow the video down so much (to show the LED sequence) that the rotor appears stationary.


So that's probably one of the most complex blog posts I've made in a while. Next time I'll be making the stepper motor run in reverse, showing how we have precise control over armature position, and if all goes well and I don't burn the house down, getting two steppers to run independently on one Raspberry Pi.

I hope.








Monday, 23 December 2013

Woooo colours!

I'm venturing into the unknown once again here, using my view that "the best way to learn is by experimenting" as an excuse for spending an hour or two with the RPi. With my ongoing mission of expanding my knowledge of interfacing software to hardware, I bought some RGB LED's from eBay (99p for a pack of 4, bargain!). Although I already know the theory behind these components, I've never actually used them before, so what better time than now to start.

An RGB LED is basically an LED (Light Emitting Diode) which has multiple anodes, each capable of outputting a different colour, in this case Red, Green or Blue,  hence the 'RGB'. There are different types of RGB LED's, but I went for the 5mm 'water clear' type, with 4 legs and a common cathode. A "common cathode" just means one of the legs acts as a single cathode for all the anodes, of which there are 3. One anode controls the Red output of the LED, another controls the Green, and the third controls the Blue. It's easiest to imagine this type of RGB LED as three separate coloured LED's rolled into one, and all the cathodes twisted together to form a single leg. Sticking with this analogy, it's worth mentioning that just like single LED's, each portion of this LED requires it's own current limiting resistor. There was no information included with the ones I bought, so I took a 'guesstimate' that a 330 ohm resistor should do the trick. It's common for the different elements of RGB LED's to require different value resistors to maintain a consistent brightness across the colour range, but that's way beyond the scope of this experiment.

It's also worth noting that 'common anode' versions are available, in which a single leg provides the power to the LED, and the user switches each cathode to ground in order to receive an output. I am assuming a single current limiting resistor is required for that type, but I could be wrong, so it's something I've made a note of to research at some point in the future. Anyway, onto the circuit...


As you can see, it's super-simple. The cathode leg is connected straight to the RPi ground, and each anode is connected directly to a GPIO pin, through a 330 ohm resistor. (Note: a 58 ohm resistor found it's way into my 330 ohm tray, and the LED didn't like it. At all. In fact, it paid the ultimate price in the name of science).

So, I wrote a very basic routine to make sure all three colours worked...


...and then embarked on a journey to make some kind of user-controllable action happen from within a Python program.

After a while, I had a basic program running which let the user choose which colour was output from the LED, with the ability to choose between Red, Green, Blue and a number of combinations of the three. Some of the colours were more overpowering than others - for example, Red and Green together created a darker Green, rather than the Yellow/Brown it should have. This relates to the resistor values and brightness intensity I talked about earlier. I could have spent some time changing resistance values to achieve better results (and I might do that one day), but this exercise was more about program control than colour accuracy. As expected, setting all three outputs on resulted in a 'white' output. Sort of.

Here is a short video of the experiment in action...


It's worth mentioning here that the output brightness of the LED can also be affected by varying the input voltage. So for example, feeding the Red anode with 3 volts will yield a much stronger Red glow than if you fed it with 1.5 volts. This is usually how you obtain a much wider range of colours - by varying the voltages supplied to each pin of the LED. Unfortunately, the GPIO pins of the RPi are either on or off (3.3V or 0V), so controlling the voltage fed to the LED isn't possible without third party hardware, or a complicated hack of components. So my next experiment will involve rapidly turning the RPi outputs on and off, hopefully simulating the effect of feeding the LED with a lower voltage. I don't expect it to be effective (or even work for that matter), but it's the finding out that counts.

For science, right?

Friday, 6 December 2013

Combining input and output.

So in my previous blog, I discovered how to get an external signal into the RPi, and read it via software. The post before that talked about sending a software driven output to external hardware. It stands to reason that this blog post should be about combining the two.

I could just use the external button to turn an LED on and off, but that doesn't really demonstrate the versatility of software to hardware interfacing. In fact, I wouldn't even need software to do that at all, I could do it all with physical wiring. So this project is about creating a 4-bit binary counter, using the button as an increment trigger and 4 separate LED's to indicate the output state, with each LED acting as a single bit in the binary number.

First, a quick rundown on how binary works. In binary, a bit (binary digit) can only be one of two states. Whether you call it "On/Off", "True/False", "One/Zero", it doesn't really matter. The point is you only get two states. This is why binary is usually thought of as Zero's and One's. The first bit (rightmost) of a binary number is "worth" 1 in decimal, the second bit is worth 2, the third is worth 4, the fourth is worth 8 etc.., so with each additional bit, the value is doubling. I've drawn this dodgy table to help explain..


As you can see, looking at the values of the columns starting on the right, they go 1,2,4,8; doubling each time. If we were playing with 8-bit binary, our sequence would read 1,2,4,8,16,32,64,128, but with the smallest number on the right of course.

Take for example from that table, the decimal number 6, and start with bit4. The value of bit4 is 8, and because that is larger than the 6 we are after, we put a 0 in that column and move onto bit3. This is worth 4. 4 is less than 6 so we put a 1 in that column, and subtract 4 from the 6 which leaves 2, and move on to the next column which is bit2. Bit2 is worth 2, which we are looking for, so we put a 1 in that column, subtract the 2, and finally move on to bit1. But after subtracting that last 2, we are left with 0. Bit1 is worth 1, so we put a 0 in that column. So we have deduced using that method, that the 4-bit binary form of the decimal number 6, is 0110; that is to say (0 x 8) + (1 x 4) + (1 x 2) + (0 x 1).

In 4-bit binary, the largest number possible is 15. Work it out. If we put a 1 in every column, we would get (1 x 8) + (1 x 4) + (1 x 2) + (1 x 1) = 15. If we need higher numbers, we need more bits, so the next generally accepted step, is 8-bit binary. The biggest decimal number possible using 8-bit binary is 255.

Okay, so you know how binary works now. Sort of. We will need 4 LED's, one to display each binary digit (bit) of our 4-bit number. Here's the circuit diagram, and it's real-world wiring to the RPi. As usual, you can click on it to see the full-size image.



So basically, the button part is exactly the same as what I discussed in the previous blog, and I've just added 4 LED's, wired each of them to a GPIO pin on the RPi, and returned each of them to the Ground (GND) rail through a 330 Ohm resistor. If you remember from a couple of posts back, the resistor is there to protect the 1.7 Volt LED from the 3.3 Volts provided by the RPi. All we need now is some Python code to control our GPIO pins, and I've done this in 3 sections...


This code just initialises the GPIO pins as an input and multiple outputs, and also has a little function which converts any given decimal number into a binary number with a user-chosen number of bits.

The middle section of code is as follows...


That part basically sets the output pins to a high value (3.3V) or low value (0V) depending on the value of a string. That string is a single bit of our 4-bit binary number. If bit1 is a "1" it sets the associated GPIO pin to 3.3V, otherwise it sets it to 0V, etc... As we are dealing with binary, there are no other options, it's either "1" or "0", "High" or "Low". No middle ground.

Finally...


This is the actual meat and potatoes of the program, the bit that does the work. It's basically a modified version of the code from my previous blog, but instead of just detecting the button presses and incrementing a counter, it converts that number to 4-bit binary (using the function I mentioned earlier), then tells the RPi to activate the appropriate GPIO pins as outputs, using the second function. Finally, if the counter exceeds the value 15, it resets it to 0.

So the idea is to show the value of the counter in decimal and binary on the monitor, and at the same time light some LED's on the breadboard, with each LED representing a single bit of our 4-bit binary number. As usual, here's the video of it in action...


For my next project, I want to learn a little more about program flow and function control, but I also want to carry on with the hardware/software interfacing, so I'm thinking of some sort of program where the user is given options, and something happens in the real world depending on the choice they make.

Either way, I'm sure it'll involve flashing lights of some description :)

Friday, 22 November 2013

From output to input...

With my very first hardware experiment completed successfully, I felt compelled to continue... for science!

So having 'mastered' the art of software-to-hardware output, the next logical step for me was hardware-to-software input. This would involve some sort of switch or button, presumably making the PC do something when I pressed it. After many hours of study through ancient tomes of historical text by candlelight (read that last sentence as 'a quick bout of google-fu'), I felt ready to start on my next project - the 'click a button and make something happen' experiment.
The circuit.

As you can see from my awesome graphic skills there, it's quite a simple circuit again. Basically, I'm connecting Pin11 of the RPi (which is GPIO17) to Pin1 (3.3V) through a large resistor. By large I mean high resistance, not physically big. I'll explain why I need the resistor in a minute, but back to the circuit...

You can also see a normally open, momentary switch which leads to Pin6 (Ground) on the RPi. So when the switch is open, it's getting a small voltage to Pin11 from Pin1. But if I push the switch, the circuit is closed and Pin11 is effectively shorted to Pin6 - the Ground. These differing states should be all we need to let the Python program know whether or not the switch has been pressed.

Now back to that resistor. If you can imagine the circuit without that resistor in there for a minute, it's obvious that if I was to press the switch, I would be shorting 3.3V directly to Ground. A dead short. Not really a clever thing to do. So the large (10K) resistor ensures that only the tiniest amount of current is drawn when the switch is pressed, thus protecting the RPi. I hope.

The code.




So the code starts with the same lines as last time, basically using existing libraries coded by some clever person somewhere, sometime. Once again, thanks, whoever you are.

I have commented the code to try and explain what each line does. The reason I needed the variable called "last_state" is because the little RPi is so quick that without it, a single button press would be read many times, and that isn't what I was trying to do. Er, how can I explain that?... I wanted to pick up one click of the button, no matter how long I kept my finger on it. Without that variable being used as a flag, holding my finger on the button would cause the program to read it as many, many clicks instead of one long one.

After a bit of tweaking and a cup of tea which seemed to go cold quicker than usual, here is a picture of the resulting output...



Here, have a video, it might make more sense...



  So there we have it. Experiment number 2 successfully completed :)

Just one more thing, the technically astute viewer might notice that I have no mouse, keyboard, or video output attached to the RPi now - just power and Ethernet. Well to be honest, I got fed up of having two mice, two keyboards, and a third monitor on my desk (I use two monitors usually), so I am now connecting to the RPi over my local network using SSH. It's like a remote desktop kind of thing, very clever and extremely handy. It also performs very, very well on this tiny little device.

Anyway, I digress. I'm cooking up ideas for experiment number 3 which will no doubt be the marriage of the two experiments completed so far. Probably, a physical input to the RPi, which is read by the Python program, processed in some way, then output physically somehow via the RPi. 

It might be time to break out the LED's again, perhaps a different colour this time as I'm feeling adventurous!

Stay tuned for the next epic adventure. Or something.

Monday, 18 November 2013

20 months later, a new project..

So er, it's been 20 months since my last blog post. Where the hell did that go? A few LAN parties, many new game releases, a few books read etc, but more recently a new project!..

You may or may not have heard about something called the Raspberry Pi . A bit of a daft name, yes. But the Raspberry Pi, or RPi as it's known, is a complete computer on a credit card sized circuit board. And it's cheap. Like £30 cheap. Not bad for a fully functional computer!

This little device is very capable, given it's price. People are using it as a media centre running a version of XBMC (it can render 1080p video over HDMI) , a lot of people are using it as an aid to learning to code, some for gaming - this thing even runs Quake 3 Arena!, and some are using it to tinker around with "other" things. And I fall into that group.

Having delved into various forms of coding over the years, from Assembler(Yuck!) to BASIC to C++ to DarkBASIC to JAVA (omg NO THANKS!) I believe the time has come for me to have a play with the hardware side of things. The RPi doesn't come with a pre-installed operating system as such, but is based on LINUX, and a number of tools are freely available for it. One language that looks easy enough to learn is Python , and this apparently works very well with the RPi. So I headed over to Codecademy and worked my way through a few basic Python lessons. Sure enough it is quite simple. At least the first few lessons are, I haven't got very far yet :)

As I said, I want to learn a little about hardware, and more specifically how it interacts and interfaces with software. The fact that a program can run within a computer and directly control real-world tangible devices fascinates me. So armed with my RPi and a few electronic bits and bobs gleaned from ebay, I set my sights on intergalactic robotic domination. But I thought I'd better start off small, so I present to you my "Python-based RPi controlled Flashing LED" project..

The bits.

Here we have the RPi itself, a 'breadboard' (for easy circuit prototyping), a few random electronic components, and a selection of 'male to female' jumper leads. As you can see, the RPi has an SD Card plugged in one end (this holds the software). Also connected here are two USB devices (mouse and keyboard), a HDMI device (monitor) and the Ethernet for Internet/Network access. If you enlarge the image (by clicking on it) you will see a row of pins to the bottom-right of the board. These are the GPIO pins (General Purpose Input Output) and these are what we use to interface to external hardware.

The circuit.

This is about as basic as an electronic circuit will get.The brown jumper is linking a GPIO pin on the RPi to the Positive leg (otherwise known as the Anode) on the LED. I have then connected a resistor to the Negative leg (Cathode) in series (more about electronic circuits in future posts unless I burn the house down first) and then close the circuit back to the RPi by connecting the black jumper to the Ground GPIO pin. The resistor is there to protect the LED because the RPi logic runs at 3.3Volts, and the LED is only 1.7V, but that's a bit technical and not for this particular post :)

So that's the hardware wired up, now onto the software. Using the free Python editor that comes with the RPi software suite, I created this program...

Apologies for the picture, I haven't learned how to do screen grabs on the RPi yet.

I've commented every line to explain what the program is doing. The part before the 'While' loop is a bit geeky, but basically I have imported a pre-defined library so that I have direct access to the GPIO pins on the board. Thank you to whoever wrote that library :)

So after some administration rights issues which I won't bore you with here, I ran the program and here's what happened...



Not exactly mind blowing I agree, but it's the first experiment of what I hope to be many. In future blogs I intend to include circuit diagrams and better screen captures. Unless something else comes along in the meantime, I'm easily distracte...oooooh, Top Gear is on... 



Thursday, 29 March 2012

Still undecided

I'm still on the fence about which project to aim for, a "resource management" type game (which I've traditionally been crap at, other than Deuteros for the Amiga...) or a "platformer" style game which I've always liked, but never attempted to write.

In my last blog entry, I posted some pictures of ideas I'd been kicking around in Paintshop, and I went on to do some base routines which involved sprite positioning and overlap detection etc, using those graphics. As I was still not committed to that project, I threw together some graphics for the platformer, and they came out like this...


...which as you've probably guessed is a series of frames from a character animation. As yet, I'm not sure if that  would be the main character, or just an NPC (non-player character). Incidentally, here's how it looks animated - I know it's not too smooth, it only has 8 frames...



...and that is my first ever attempt (as far as I can remember) at sprite-based character animation.

Sooooooo, I'm still on the fence about which project to go for. Either way, I have a 4 day LAN-party rapidly approaching, so I doubt I'll be doing much coding then. Having said that, the last time I was stuck with a networking issue, an abundance of Magners helped me out...


Thursday, 22 March 2012

Kicking an idea around

So I've been messing about, trying to come up with some idea of which direction I want the next project to take. I really want to try my hand at making a platformer at some point, and also some sort of resource management-type thing.

The platformer I have an idea how to start, it's pretty straightforward (he says, as if he knows what he's doing...) whereas a resource management game would be totally new to me. So I started throwing together some in-game art to see if it would lead me anywhere. I'm still working on the platformer art at the moment, but regarding the resource game, after half an hour with PaintShop this appeared...


...then an hour later, this...


I have a very rough idea for a game based on those graphics, but nothing solid enough to start coding. I'm going to see how the platformer graphics pan out before committing to anything. But, back to work tomorrow, so I'm not sure how long it will be before I get something off the ground.