A Programmable Layout Controller

Programming an Arduino to run turnouts, lights or animation on the layout is only part of the challenge. The other part is how do you control the board and tell it what you want it to do?

Servo Control with LED Feedback

Servo Control with LED Feedback

From an Arduino point of view, any sensor attached to a pin can trigger action in a sketch. As shown in Turnout Control with Arduino & Servos, mechanical buttons and switches can be attached to pins to tell the board what to do. In the example circuit, a single button triggers servo action. If you want to include feedback indicators as in this example circuit — these could be layout signals or panel indicators — you can hard-wire everything together to the same Arduino board.

Until you run out of pins

Pin management is critical as you ask the Arduino to do more and more. Every new sensor or triggering device consumes pins (as does every new actuator or output device). While learning what I could do with an Arduino on the layout, I realized that I needed get beyond the hardwired controls used in experiments and demos to a generic, software-based control system. To do that I was going to have to network everything together.

Networking Arduinos

Uno with Ethernet Shield

Uno with Ethernet Shield

In Roundhouse Rebuild Part 2 I mentioned, without explanation, that I was using Ethernet, and went on to discuss the evolving Simple Network Command System. I decided to go with wired Ethernet because of the easy availability of inexpensive Ethernet shields based on the WIZnet W5100 Ethernet Controller chip (under 10 dollars per shield), and an easy to use Arduino library included in the IDE. It is as close to plug & play as networking gets on an Arduino. The only additional equipment required are one or more inexpensive 10/100 switches (for example: TP-LINK TL-SF1005D 5-port 10/100Mbps Desktop Switch; don’t get gigabit switches to work with these shields, you’re just asking for trouble) to  interconnect the devices. I use a per-device assigned address system which helps keep the equipment roster simple (no router or DHCP required).

Why not just use the Digital Command Control system for the Arduino net? The short answer is that while it is clearly doable, for the purposes of this project I am going to keep the Arduino net separate because:

  1. Everything I do here has to work for both DC and DCC layouts. I own both DCC and unconverted DC locomotives; the layout has to work the same in either mode.
  2. Compared to conventional networking, DCC is a relatively difficult way to conduct bidirectional communications between Arduino boards.
  3. Keeping them separate does not preclude enabling communication between the two systems down the road.

If you want to pursue DCC communication and Arduino, the Model Railroading with Arduino site is a great place to start. The biggest impediment for most modelers will be the lack of commercial interface hardware to connect an Arduino to either track power or the command bus (although the circuits are easy enough to build); the closest commercial solution would be to use a USB interface, like the Digitrax PR3XTRA USB Programmer, RR-CirKits LocoBuffer-USB or the SPROG II USB, to tap into the DCC command system just as you would with JMRI.

My ultimate goal is to build the layout’s electronic and mechanical foundation around a network of Arduino boards. For communication among Arduino boards, Ethernet makes the most sense right now because it is the most “frictionless” route to achieve my goals (a wireless form would be even better, but would be a little more difficult to implement, so I’m holding that option for the future); communication between the Arduino net and the DCC system is a topic for the future—and the possibilities go way beyond treating Arduinos as decoders.

Building The Controller


Adafruit 3.5″ TFT screen displaying a bitmap.

The concept for a prototype controller was simple enough: start with an Uno, add an Ethernet shield and add a small touchscreen for display and user input. Put it all in a box with an Ethernet jack, a USB jack and power connector. Software generates screen displays, interprets touches and communicates with devices it is controlling.

For the screen I chose the Adafruit 3.5″ TFT Touchscreen, seen here attached to an Uno via a breadboard (NB: The wiring shown is the minimum required to run the screen; the touch overlay and the SD Card reader require additional connections). It is capable of full 16bit color with a resolution of 320 x 480 pixels. The Adafruit library provides basic graphic primitive functions, basic text functions and bitmap functions allowing image display. It has a resistive touch overlay. Adafruit has an excellent tutorial on using this screen with their library.

Back of 3.8" TFT Screen

Back of 3.5″ TFT Touchscreen

The screen comes with a choice of interfaces: you can use the SPI bus interface in order to use the fewest pins on your Arduino, or you can devote more pins to use the faster 8 bit interface. You select the interface and solder the header pins on the appropriate side.  A  solder jumper on the back determines which interface is active; the decision is reversible. An SD Card reader is included for convenient storage of bitmap files.

On an Uno, the Ethernet shield dictates that the TFT screen has to be run via SPI; there aren’t enough pins otherwise. The application does not require the SD Card Reader so I don’t connect it to the UNO.

I fabricated a wiring harness for attaching the screen to the Uno\Ethernet combo, then mounted everything in a Radio Shack project box as shown below.

Wiring Harness

Wiring Harness

The connectors on the wiring harness are male or female PCB Headers; I solder the wires to the PCB side of the fittings, then cover each connection with heat shrink tubing. White wires connect to digital pins 7 through 13 (except 10, which is reserved for the Ethernet shield) and are for the TFT interface. Green wires are for the touch overlay and connect to Analog pins A2 – A5. Red supplies 5v, and black ground, to the TFT screen. The Ethernet extension cable and the USB extension cable both came from Adafruit.

Inside the Controller

Inside the Controller

Controller with Screen Wiring Attached

Controller with Screen Wiring Attached








Here it is in operation:

The Programmable Controller

The Programmable Controller







You may have guessed the fan ( on the left side ) was an afterthought. The cheap Ethernet shields I use are heat sensitive; they will crash when put in a confined space with poor air circulation.  Out in the open no problem; in a box, its a problem. Found that out the hard way. So I added a little fan to pull the air through the box (if you look closely, you’ll see there are holes around the bottom); works fine if noisily. Obviously, I will plan for air circulation when I build the main layout control panel. Such is prototyping!

What it Does

The controller sketch displays menus with buttons that, when touched, will cause the controller to either go to a different menu or send a command packet to the target device. Command packets are strings, formatted thus: function / option / data. For more about my protocol and the network polling process, see the Simple Network Command System section near the end of Roundhouse Rebuild Part 2.

The Main Menu provides access to sub-menus that I’ve created to support parts of the project.

Controller Main Menu

Controller Main Menu

All menus are built with buttons. A structure type called button_t holds button data:

typedef struct {
  int x;
  int y;
  int txtX;
  int txt;
} button_t;

X and y are the coordinates of the upper left corner of the button; the width and height are the same for all buttons in this version of the system. txtX is the x coordinate for the button text; the y coordinate is calculated and there is no text centering function. Finally, txt is an offset into a button_labels array pointing to the button text.

For the main menu, the button set definition looks like this:

const button_t buttons_main[SIZE_MAIN_SET] = {
  {90, 80, 115, 0 },
  {250, 80, 254, 1},
  {175, 140, 185, 16}};

Determining if a button has been touched is fairly straight forward. The coordinates of a touch p are compared to each button, as b, in the current set to see if it is on or within the button boundaries.

p.x >= b.x && p.x <= (b.x + BUTTON_WIDTH) && p.y >= b.y && p.y <= (b.y + BUTTON_HEIGHT)

Whacking My Head on the Memory Ceiling

The graphics libraries contain a lot of code. With the newest Arduino IDE, the controller sketch compiles to 27,030 bytes, about 83% of available program space; it was about 29k bytes with the previous IDE.

That is still tight enough that I cannot include SD Card access and a function to draw a bitmap from a file without going 15% over the absolute memory limit for an UNO. In the future I’ll use an Arduino MEGA 2560 Board instead of an UNO for control panel applications because of its vastly superior memory resources (and it has a lot more pins to work with). The remaining 17% with the current sketch gives me plenty of room for now.

The trickier bit of memory management is “dynamic memory,” which (on an UNO) is 2,048 bytes of shared memory space used for local variables. Local variables are created when functions are called and destroyed when they are exited. Global variables–variables declared outside of any function that are always in scope and available wherever you are in your sketch–are also stored in the same space. Global variables reduce the amount of dynamic memory available for local variables and, if not managed, can strangle your sketch.

Fortunately, the majority of global variables turn out to be constants — unchanging values or text used by the application. This kind of data can be stored in the program space instead of dynamic memory; the limitations are that

  • you can’t change the value stored in program space while the sketch is running, and
  • you have to copy a value from program space to dynamic memory in order to use it.

The PROGMEM keyword is used to tell the compiler to store something in program space instead of dynamic memory. To park menu titles and button text in program space, I did this:

const char mstr_0[] PROGMEM = "Main Menu";
const char mstr_1[] PROGMEM = "Lighting Menu";
const char mstr_2[] PROGMEM = "Roundhouse Menu";
const char mstr_3[] PROGMEM = "Test Loop Menu";

const char* const menus[] PROGMEM = {mstr_0, mstr_1, mstr_2, mstr_3};

const char str_0[] PROGMEM = "Lights";
const char str_1[] PROGMEM = "Roundhouse";
const char str_2[] PROGMEM = "<-Back";
const char str_3[] PROGMEM = "  Night";
const char str_4[] PROGMEM = "   Day";
const char str_5[] PROGMEM = " Mid-Day";
const char str_6[] PROGMEM = " Sunrise";
const char str_7[] PROGMEM = " Sunset";
const char str_8[] PROGMEM = "   Low";
const char str_9[] PROGMEM = "  High";
const char str_10[] PROGMEM = " Stall 1";
const char str_11[] PROGMEM = " Stall 2";
const char str_12[] PROGMEM = " Stall 3";
const char str_13[] PROGMEM = " Stall 4";
const char str_14[] PROGMEM = " Stall 5";
const char str_15[] PROGMEM = "Afternoon";
const char str_16[] PROGMEM = "Test Loop";
const char str_17[] PROGMEM = "Main";
const char str_18[] PROGMEM = "Siding";
const char str_19[] PROGMEM = "Occupancy";

const char* const button_labels[] PROGMEM = {str_0, str_1, str_2, str_3,
 str_4, str_5, str_6, str_7, str_8, str_9, str_10, str_11, str_12,
 str_13, str_14, str_15, str_16, str_17, str_18, str_19};

Copying the title of the main menu into a local variable text looks like this:

strcpy_P(text, (char*)pgm_read_word((&menus[0])));

For getting the button labels:

 strcpy_P(text, (char*)pgm_read_word((&button_labels[b.txt])));

An alternate way to store static data in program memory is to use the F macro, as in this declaration of a local variable that initializes with a static value that is stored in and retrieved from program memory:

String readyStr = F("Ready");

At this point I find it useful to make it a habit to use these tools in all sketches to tame dynamic memory space. Currently the controller sketch uses only 771 bytes or 37% of dynamic memory for global variables, leaving plenty of space for locals.


The Lighting and Roundhouse menus look like this:


Lighting Menu


Roundhouse Menu

Roundhouse Menu

These are the controls I used off screen to control lighting when making the Roundhouse demo video. Overhead lighting was supplied by 4 led light bars (152 RGB ALEDS total) controlled by a networked UNO.

I’ve been busy at the test loop trying out various ideas.  Turnout control, signals and block occupancy detection (I have a method that works for both DC and DCC layouts), all play a part in the next step toward the layout. I’ll leave you to ponder the test loop menu until next time.

Test Loop Controls

Test Loop Controls




Model Railroader, Meet Arduino

I was not even slightly surprised when I opened the December 2014 Model Railroader Magazine, to encounter “RFID for Model Railroad Operations.” There seems to be considerable interest in RFID among model railroaders, enough that there is JMRI support available, and this project looks like a particularly nice piece of work.

The illustrations caught my eye and I recognized that at the heart of their system is an open source microcontroller board called the Arduino Uno.

Arduino Uno R3

Arduino Uno R3

You have to know what you are looking at, or dig into the article to get that bit of information.  A one sentence editor’s note explains that Uno’s are “simple computers that can be programmed to do many useful model railroading tasks.”

Oh, my.  That’s no way to introduce a hobby to a new dance partner. We’ve met once before in the June 2013 Model Railroader Magazine article “High Tech Turnout Controls.” But everyone was a little shy back then, there was really not enough information about the new partner to truly understand its potential. Referring to unseen computer code that has to be compiled and uploaded was probably a bit frightening to some. And, I suppose it didn’t help that the servo installation presented was, shall we say, a little too utilitarian.

No matter. Lets start over and get the introduction right this time, because the dance has already begun!

What is a Microcontroller?

Microcontrollers are integrated circuit chips that have the basic logic and input/output capabilities that constitute a simple computer. Microcontroller boards place that chip with a few essential external components on a board with power and ways to plug things in. Microcontrollers have been around for a long time; you’ll find them in almost everything electronic.  What’s new is how inexpensive the chips and supporting components have become.

The best known, and by far best developed open source microcontroller board system is the Arduino Project. In their words:

Arduino is a tool for making computers that can sense and control more of the physical world than your desktop computer. It’s an open-source physical computing platform based on a simple microcontroller board, and a development environment for writing software for the board.

Microcontroller boards like Arduino are simpler than microcomputers like the Raspberry Pi or the Beaglebone.  Aside from differences in the controller/processor used, the big difference is that microcomputers come with more peripheral components and memory to allow them to load an operating system.  You don’t generally use an “operating system” with a microcontroller: rather the board is designed to run whatever code you’ve loaded in the board’s permanent memory. In essence, your program is the firmware/operating system for the board.

The Arduino interacts with the physical world using sensors and actuators. Sensors can be anything that responds to an external influence:

  • buttons and switches,

    micro button

    Micro Push Button

  • optical sensors, such as photoresistors, IR/UV and so on,
  • current and voltage sensors,
  • touch and proximity sensors,
  • RFID sensors,
  • GPS and other position sensors, include tilt and acceleration,
  • USB and various kinds of network communications,
  • anything that can produce a 0-5v current to signal its state, either as an on/off (digital) signal, or as a variable current (analog).
Combination accelerometer, Gyro and Magnetometer

Combination accelerometer, gyro and magnetometer

Sensors can be a single chip/component, or another board or external assembly that communicates with the Arduino.

The code you upload to the Arduino can read the sensors and take logical actions based on those readings.  It takes actions by controlling actuators. Actuators include:

  • AC/DC motors,
  • servos & steppers,
  • switches, relays, transistors and other current amplification and modulation devices,
  • LCD’s, LED’s, OLED’s both individually and in arrays up to and including small screens,
  • USB and various kinds of network communications.
Adafruit TFT Touchscreen

Adafruit 3.8″ TFT Touchscreen and an Uno

Adafruit Industries has the above touchscreen, along with a lot of other cool sensor and actuator devices to use with Arduino.

Stepper motor.

Stepper motor.

The basic structure of an Arduino sketch (program) is a continuous loop that checks the sensors and acts as required. Depending on the complexity of the sketch, the basic sense/act loop can cycle hundreds or thousands of times per second. Since you are directly interacting with the hardware without an operating system, your sketch has fairly precise control of all interactions.



The Arduino is a teaching and learning tool.  If you don’t know anything about computer programming, this little board was designed for you! You don’t really have to know C++ (the language used by the development tool) as such; you just have to learn and follow the basic rules as applied to the Arduino, all laid out in the tutorial system. If you can do basic math and logic, you can learn this.

If anything, novices may have an advantage over folks who program larger and more complex systems–who may have to rethink a few habits to adapt to the limits of the Arduino. The Arduino IDE hides most compiler preprocessing, which is great for newbies and lousy for those used to having total control of the preprocessing/compiling process.

Lets take the basic use case–turnout control–as discussed in the June 2013 MRR article. I’ve done a little Q&D on the basics of setting up and using a servo for turnout control; take a look to see what the code looks like. It’s a lot more straightforward than you might expect.

But What’s it For?

So turnout control is one use, but it may not be entirely clear why this is better than traditional turnout motors and wiring. From my point of view, it comes down to leverage: getting a lot more functionality for the money.

Given that a single Arduino Uno ($25) can support multiple micro servos costing $2 – $4 each, its easy to see how an Uno running 4 turnout servos is saving money; even more if one Uno can manage an Yard full of servos. Other functions that might be handled by accessory contacts on an expensive turnout machine can be handled easily by the Arduino at the same time, like running signals, managing track power relays or triggering other systems. As you stack related functionality onto a network of Arduinos, instead of investing in multiple single-purpose systems, the combined enhanced functionality and cost savings of this approach becomes quite compelling.

Among model railroaders on the web who are working with Arduino, the most common thread I’m finding is to use the Arduino as an adjunct to the DCC system. An obvious approach is to use a stationary decoder as a “sensor” that the Arduino responds to with whatever task you have in mind — for instance, this would work well where the Arduino is an animation controller.

To get an Arduino and DCC system to communicate with each other without a decoder, you could use the generic USB interface, which most Arduino boards and many DCC systems support. Since DCC systems don’t speak Arduino, something like JMRI is needed to glue it all together.

Others, like the Model Railroading with Arduino project, an off-shoot of the Open DCC Project, are working on direct Arduino/DCC interfaces. It’s pretty straight forward to interface an Arduino with the DCC command bus. Check out this project using an Arduino Mini to create a 17 function DCC decoder. As to the unreasonably low price the author reports for his Arduino Mini Pro, please see this post about Arduinos, compatibles and counterfeits. If you find these things useful and want the benefits of further development, then you should care about the ecosystem. An official Mini Pro from SparkFun lists for $9.95. and a portion of its proceeds are given back to the Arduino Project.

Controlling turnouts with servos and an Arduino, RFID decoding or even creating a “programmable DCC decoder” using an Arduino represents a small fraction of the potential of these devices. The trend today seems to be toward greater centralization of model railroad control systems. Embedded microcontrollers can be a step down that road as well, adding considerable functionality as “decoders with brains”; or they can take you in an entirely different direction–where semi-autonomous logic devices controlling different aspects of the layout interact with each other and with the operators in dynamic ways.

I’ll give a little more substance to these ideas as this project progresses.