PICAXE Model Railroad Speed Controller
d. bodnar


Since 2004 I have been singing the praises of the PICAXE family of microcontrollers to fellow model railroaders through articles on my web page (http://www.trainelectronics.com ) and through presentations at national and regional model railroad conventions. 

Throughout this period I have wanted to put together a complete kit that would allow beginners to start working with the PICAXE while building a useful model railroad accessory.  The new PICAXE 18M2 chip inspired me to write this article and assemble the parts for the kit that accompanies it.  The completed kit is a full-featured model railroad speed controller with many innovate and interesting features and capabilities.  If you are not into model railroading I am sure that you will discover that the controller can be used for any number of other control projects as well due to its flexibility and the fact that the controller is completely solid state and will work with any 3 volt to 35 volt DC motor.

The unit is designed to be a track-side power controller that can operate any model train that works with direct current (DC) and pulls 3 or fewer amps (that includes most of our trains & trolleys).  It is operated by means of a simple TV infrared remote control unit.  In its most basic mode of operation the controller allows you to increase or decrease the speed of a train and reverse the train's direction with the handheld TV remote.  This is an ideal way to operate the train under the Christmas tree!  In point-to-point mode the controller can be programmed to automatically run the train in one direction for some number of seconds, decelerate it, come to a complete stop, reverse and continue on in the other direction.  This makes it a perfect controller for a small work train or a trolley.  I also have plans to use one for my incline and a cable car.

Additional modes and functionality can be added by the hobbyist through simple editing of the PICAXE BASIC code allowing the controller to operate onboard a train or as a controller for animations on your layout.

Since it is able to control the speed and direction of any DC motor it can also be used with any number of other projects including robotics, animation and holiday exhibits. 

Endless Possibilities
A second article will show you how a few components can be added to this circuit so that it becomes a unique device that will not only allow you to control the speed and direction of a train but to record a series of movements over many minutes and play back the same sequence of moves over and over.  This is a super way to add variety to demonstration or self running train layouts.  I plan on using this controller to operate the layout that we maintain at Pittsburgh's Children's Hospital.  Rather than just having the trains run in a simple loop, the recording controller will have the trains running, stopping, reversing and giving a more varied sequence of movements.

Control Options
One of the most difficult tasks one faces when designing a microcontroller based device is creating a user interface that allows the operator to control the unit with ease.  Because the PICAXE 18M2 has the ability to interpret and act upon codes sent from a simple TV remote control the user interface can be both full featured and easy to use.  The device shown below is a Westinghouse brand unit that only sends the Sony codes that the PICAXE is programmed to interpret.  Most Sony and multi-brand programmable remote controls will work.  It is possible that some of the buttons will not match what is shown here but is it a simple matter to modify the code to work with another remote control.

This TV remote control's buttons are used as follows:

Using the Controller
The video shows many of capabilities of the controller. 

(right click on the box below and select Play or click HERE)

The 18 pin PICAXE 18M2 is the brains behind the controller.  This new member of the PICAXE family is an extremely capable chip that is well suited to the demands of this project. 

The "brawn" comes from a single chip, the L298N H-Bridge.

This 15 pin device is responsible for controlling the direction of travel and the speed of the train.  It is called an "H-Bridge" due to the fact that such devices are frequently drawn in a schematic with four transistors in an "H" pattern.  I like to think of an H-bridge as a solid state double pole double throw switch.  As you may know a DPDT switch can be wired so that it delivers power to a train with one polarity setting in one position and with the opposite polarity in its other position.  When DC motors have their polarity reversed their direction of rotation is reversed as well.

The infrared codes from the hand held remote control are received by a small chip, the Sharp GP1UX511QS.  Its small, boxy case and three leads belie its complexity.  Inside is a sophisticated circuit that receives the 38 KHz infrared data stream from the TV remote control and filters it into a series of pulses that are easily interpreted by the PICAXE.

Other components include indicator LEDs, a voltage regulator and assorted resistors, capacitors and diodes.  All in all it is a straight forward circuit that works very well with loads of up to 3 amps.  DC power is supplied by any filtered power supply providing 12-24 volts.  I have had great success using old laptop power supplies for this and other projects.  Be sure to use an appropriate heat sink on the L298N if current is likely to exceed 1 amp.

How It Works
The PICAXE is programmed through pins 2 and 3 which are connected to the computer's serial port (or to a USB to serial adapter).  Resistors R1 and R2 are all that is needed to connect your computer to the PICAXE for programming. 

Infrared pulses are generated by pressing a key on the TV remote control.  These are received by the IR receiver IC and sent to the PICAXE through pin 8.

All of the power control is done with pins 6, 11 and 9 on the PICAXE.  These pins control the output of the L298N H-Bridge.  The L298N is designed to operate two separate motors each drawing up to 2 amps.  In this application we are only controlling one motor so its control & output pins have been wired in parallel so that one motor can be supplied with up to 3 amps of current.  When the PICAXE's pin 6 is high and pin 11 is low the motor is set to rotate in one direction.  When pin 6 is low and pin 11 is high it rotates in the other direction.  LEDs D2 and D4 light to show you which direction the L298N is set to.

When the microprocessor needs to change the speed of the motor it sends a series of pulses, called Pulse Width Modulation, to the enable pins on the “H-bridge”.  This spins the motor at full speed if it sees 5 volts and stops the motor if it sees 0 volts.  A voltage between 0 and 5 volts gives a speed proportional to the voltage.  Microprocessors generally don’t deal well with variable, or analog, voltages.  That is where PWM comes in.  PWM sends a series of 5 volt pulses to simulate a variable voltage.  For example, if it sends pulses that are on ½ of the time and off ½ of the time the pin appears to have half of the supply voltage or 2.5 volts on it.  Sending pulses that are on 25% of the time and off 75% of the time looks like 1.25 volts and so on. (see graphic). 


The parts that are used to build the controller include:

This photo shows the parts arranged near their intended location on the circuit board.

These two photos show the completed board.

The Rest of the Board
You may be wondering about the unused areas on the board, those shown boxed in yellow below.  These areas are for additional components that are used in the next phase of this project where the controller is used to record and play back a train's movements.  They will be utilized and fully described in the next article.  Stay tuned!


Construction and Step-by-Step Testing
Although this circuit can be constructed on a number of different prototyping circuit boards the easiest way to make it is on a custom circuit board that was designed and fabricated to do exactly what is shown in the schematic.

Start by installing the voltage regulator, tantalum filter capacitor and the PICAXE socket.  The 7805 voltage regulator must be installed as shown in the photos.  The tantalum filter capacitor has a small + on it and must be oriented so that the + lead goes into the hole marked with a +.  Be careful as there is another set of holes nearby that are also marked "Cap" but they are for another capacitor that will be installed later.

Once this is complete you can apply power and check pins 5 and 14 on the socket for +5 volts.  Be sure that you connect the power leads correctly to the pins labeled "DC in".  The pin marked "+" gets the positive voltage and the pin marked "-" gets ground (negative).  Set your volt meter to the DC scale and test between pin 5, negative, and pin 14, positive.  The meter should show 5 volts plus or minus a tenth of a volt.

5 Volt Test Video 
(This and the other test videos were done with an earlier version of the circuit board but still accurately represent the tests with the newer board that is shown in the photos.)

(right click on the box below and select Play or click

LEDs and Resistors
There are six 470 ohm resistors that limit the current going to each of the LEDs.  Bend the resistors as shown and install them in the marked holes in the board.  Remember that resistors can be inserted either way.  Solder them to the board from the back and trim off the leads that remain.  I found that a 4.7K resistor worked better with the green activity LED as it shows the variable PWM voltage more gradually as the speed increases.  You can try any value from 470 ohms to 10K to get a good brightness for this LED.  You will note that the resistor value printed on the latest board is marked 4.7K.

Insert the six LEDs into their locations on the board.  LEDs are polarity sensitive and must be installed properly.  The notch on the LED is the cathode, or negative lead.  It is marked on the board showing the flat side of the LED.  The cathode lead is also the shorter of the two LED leads.  Push each LED close to the board and solder from the back.  Trim off the leads after soldering.

Install the 10K and 22K resistors that are part of the programming circuit.  At this point the PICAXE can be installed and tested with the programming software.  Please be sure to insert the PICAXE chip so that all of its pins go squarely into the socket (none are bent underneath) and that the notch on the end of the PICAXE is located close to the edge of the board.  The three pin connector just above the red LED is used for programming.  The negative lead of the programming connector is to the right and is marked with a small "-" sign.

Here the matching three pin plug has been inserted. 

Start the PICAXE programming editor.  This free program is available for download at http://www.picaxe.com/Software

When the program starts it normally displays a set of options as shown here.  If this is not shown click on View from the main screen then Options.  Make sure that the PICAXE mode is set to PICAXE-18M2.

Click on "Check Firmware Version" to test your circuit.  You should see a message similar to the one shown below.  If it is not displayed check your serial port settings under the "Serial Port" tab and try again.  When you see the message below displayed the PICAXE and the software are "talking" and the microcontroller can be programmed.  If you have difficulty reread the serial connection sections in the PICAXE Getting Started Manual.  There is also information on serial programming problems on the PICAXE forums at http://www.picaxeforum.co.uk/ .

To test the LEDs load the LED_TEST.BAS program into the program editor, connect the board to the programming cable and power.  Click the "Program" button at the top of the screen.  Once the program has been downloaded to the PICAXE you should see the amber, blue, green, red, small green and small amber LEDs flash in sequence.  If any of the LEDs does not light check your solder joints and the orientation of the LEDs in the board.  If they are inserted backwards they will not light.

 LED_TEST.BAS Program:

Symbol Direction1 = b.5 'pin 11
Symbol Direction2 = b.0 'pin 6
Symbol IRSense = b.2 'pin 8
Symbol LEDBlue = c.7 'pin 16
Symbol LEDAmber = c.6 'pin 15
Symbol Motor = b.3 'pin 9

HIGH Motor:PAUSE 500
HIGH Direction1:PAUSE 500
HIGH Direction2:PAUSE 500

LOW Direction1
LOW Direction2
LOW Motor
PAUSE 1000

LED Test Video
(right click on the box below and select Play or click

Infrared Sensor:
Insert the infrared sensor into the holes that are labeled "ir sensor".  The dome on the sensor must point towards the amber, blue and green LEDs and away from the red LED. 

Solder its leads leaving the sensor as far above the board as possible.  If desired the sensor can be moved closer to the board later on but it is better to leave the leads long for testing.  If you are planning on putting the finished unit into project box you may want to connect the IR sensor's leads on wires so that it can be placed on the outside of the box.  In this photo the sensor is plugged into a 3 pin female header so that it can be removed and repositioned as needed.

Here the board is almost done.  Just the H-Bridge is missing.

To test the sensor load the IR_TEST.BAS program into the editor, connect the board to the programming cable and power.  Click the "Program" button to load the software.  When programming is done click OK to get rid of the "Programming successful" box.  Click the PICAXE tab then click "Terminal...".  The terminal screen will appear.  Make sure that 4800 is selected as the Baud Rate and that the programming cable is still attached.  Aim the TV remote towards the sensor and press a button.  You should see its corresponding code displayed on the terminal.  Note that you can skip this step if you insert the directive (#Terminal 4800) that is shown in the IR_TEST.BAS program as the terminal screen will automatically be displayed.

IR_TEST.BAS Program:

#terminal 4800   'Directive to start terminal at 4800 baud after programming
#no_data         'Directive to not download data - speeds up programming

Symbol IRSense = b.2 'pin 8
Symbol InfraRED = b12


Irin [50, IRTEST],IrSense, InfraRED

SERTXD("InfraRED Code = ",#InfraRED,13,10)

IR Codes Test Video
(right click on the box below and select Play or click HERE

This is also a good time to test your TV remote control, especially if it is not the same as the one used here.  This table shows the buttons that are used and the codes they produce:
TV Remote Key Code
Volume Up 18
Volume Down 19
Channel Up 16
Channel Down 17
Mute / OK 20
Return 59
1 0
2 1
3 2
4 3
5 4
6 5
7 6
8 7
9 8
0 9

If you find that any of the codes that your remote control generates are different than those above be sure to make appropriate adjustments in the program.

Other Parts:
Install and solder the two small capacitors.  Their orientation does not matter but be sure to put them as close to the board as possible.  Bend the leads on the four diodes and insert them into the board.  Note the band that is marked on each diode and the corresponding mark on the board making sure that the diodes are oriented correctly.  It may take a bit more heat to properly solder the diodes as their leads are thicker than the leads of the other components.  Clip off the leads and check for solder bridges.  The parts list shows that you can use either standard silicon diodes (1N2004, for example) or high speed Schottky diodes.  I have tested the boards with both types of diodes and have found that the circuit works equally well with either type of diode.

Install and solder the two pin connector labeled "track".

Insert the L298N's fifteen leads into the circuit board.  It may take some gentle bending of the leads to get them all in.  They do not need to go very far through the holes, just enough to get a good solder joint.  Here the L298N's leads are shown from the back of the board, before soldering.

This photo shows the L298N after its pins have been soldered.

The last small capacitor goes on the back of the board between pins 5 and 14 on the PICAXE.  Cut its leads before inserting and soldering to the board. 

The board is now nearly complete.  Add the heat sink to the L298N if you will be using trains that draw more than 1 amp.  For smaller trains that draw little current it may not be needed.  In addition you should add a two or three amp fuse to the power input connection.  You can also use a polyfuse that automatically resets after an over current issue is cleared. 

Simple test program (fast / slow / fwd / back)
This program can be used to test the entire circuit.  I wired the track power output directly to a small DC motor.  The program starts the motor spinning in one direction, lets it run for a few seconds, gradually slows it down, reverses it and repeats.  Take special note of the subroutines in the program.  These are used in other variants of this program and really simplify writing and debugging code.  REVERSE, ACCEL & DECEL are the three subroutines used here.

'd. bodnar 6-21-2011
#terminal 4800 'Directive to start terminal at 4800 baud after programming
#no_data 'Directive to not download data - speeds up programming
SYMBOL Direction1 = b.5 'pin 11
SYMBOL Direction2 = b.0 'pin 6
SYMBOL Motor = b.3 'pin 9
SYMBOL Loop1 = b27
SYMBOL ADRate = b16
SYMBOL MinSpeed = w3
SYMBOL Loopie0 = W1
SYMBOL SetSpeed = w2
PWMOUT motor,50,500 '150 ; set PWM duty
HIGH Direction1:LOW Direction2
PWMDUTY motor, SetSpeed

SERTXD("d. bodnar",13,10,"6-21-2011 Motor Test 3.2",13,10,13,10) '4800 baud @ this clock speed


SERTXD("Pausing 5000 millisecods",13,10)
PAUSE 5000
GOSUB revers
GOTO Cruise

GOSUB decel
SERTXD("Pausing 1000 millisecods",13,10)
PAUSE 1000
TOGGLE direction1:TOGGLE direction2
GOSUB accel

FOR loopie0= MinSpeed TO SetSpeed STEP 5
SERTXD(#loopie0," ")
PWMDUTY motor,loopie0 ; set pwm duty
PAUSE adrate
NEXT loopie0

FOR loopie0= SetSpeed TO MinSpeed STEP -5
SERTXD(#loopie0," ")
PWMDUTY motor, loopie0
PAUSE adrate
NEXT loopie0

Motor Test Video
(right click on the box below and select Play or click

Latest and Greatest Control Program
The most up to date version of the software (the one that was used for the first video) and some notes on its operation are here: 

I hope to update and expand the capabilities of the controller by modifying the software as I and other users of the controller make changes.  Check back often for the latest version.

Use on-board trains
While the circuit was initially designed for use as a track-side controller for G-scale, HO and other DC operated trains, there is no reason that it could not be installed on-board a locomotive, tender or boxcar of a larger scale train.  I have successfully installed this and similar circuit boards in a number of G-scale and O-scale engines and trolleys.  They work great  You just need to mount the IR sensor so that you can "see" it with the remote control to make changes in speed or operation.  Some of the trains I have used in this way have operated from fixed voltage track power.  I have used both AC and DC.  AC has worked best for me.  To use AC a bridge rectifier and filter capacitor need to be added to supply power to the board.

Going Further
There are a number of pins from the 18M2 that are not used and can be employed in a number of ways. 

The point-to-point controller could be redesigned so that reed switches along the track were activated by a magnet on the train so that the train slows and stops at a station and then continues on its way.  Reed switches could also be employed to reverse the train at the end of the track.

Up to four of the extra pins could easily be connected to one of the inexpensive MP3 sound units described here:  http://www.trainelectronics.com/USB_Sound_4/index.htm.  The program could be modified to sound a bell, whistle or horn when the train stops, starts or slows down.  Even though the sound would not emanate from within the train or trolley a speaker could be hidden within the layout to give the illusion that it was.

A Kit is Available
A kit that is made up of all of the parts shown in the article is available from the author.  All you need to supply is a power supply and a motor to control.  The cost of the kit is $65 + shipping.  I can also supply a wired and tested unit but my hope is that most users will enjoy the experience of building the kit themselves.

Programming Cable
You will also need to make up a programming cable to connect your computer to the PICAXE.  There are three options:

  1. If you have a computer that has a 9 pin serial port you can make a programming cable following steps 9 and 10 in this article:  Robot Trains in the Garden.  All that you need is a three pin connector and a DB-9 connector.  These parts can be ordered with the kit.
  2. If you don't have  a serial port you can purchase a USB programming cable here: USB Cable.  Since this unit ends in a 3 pin phono jack you will need  to have an adapter.  This adapter can be ordered with the kit.  It is wired as shown here.
  3. You can also use a USB to Serial Converter to give your computer a 9 pin serial port.  Once you have the converted installed you can use the cable described in the first option.

As usual, please let me know how I can help.   dave@davebodnar.com