L&NC Update; Running Lots of Turnouts

Its been a long stretch where there has been too much going on in real life and little time to write about model railroading. But I’ve been working away on the first module of the L&NC and have made lots of progress, so there’s plenty to write about.

This module has nine turnouts, presenting resource management problems that would arise in any substantial yard or staging facility. If you are familiar with the servo library then you know that you are limited to about 10 servos per microcontroller. With that many servos, your microcontroller will have few resources left to do anything else. This post will focus on a solution that problem, expanding the number of servos and other PWM devices a single microcontroller can manage.

Progress Tour

But first, a quick overview of progress to date.

Here’s the module in its current state:

Progress on the 1st Module as of June 2017. Fascia and dressing up of the edges will be the very last step; its pointless to do that while I’m disturbing things with new features and gear. Wires hanging out the pipe at the bottom of the photo are Anderson Powerpole connectors (track and master power) to the upper level.

As you can see I’ve done quite a bit of detailing. I realized early on that I need to complete all the basic scenicking and detailing of the module before moving on to the next. The big reason is having the module alone on a work table gives the best possible access, especially for electronic or animated items that require access to the underside. That’s not to say detailing will not continue after I move on to the next module, but it will mostly be passive rather than active elements.

By the way, if I were to build a room-sized layout, I’d use a modular (some call it “sectional” because you build it in sections) approach to construction even though the layout would not be portable. After laying mainline and other track spanning sections and cutting gaps between sections, I’d pull each section and do most of the remaining work in a work area under optimal conditions. When ready its just a matter of returning the section to its place in the layout and (literally) plugging it in.

Lets take a quick tour of some details so far.

Roundhouse / Turntable

If you’ve read the previous posts about the Roundhouse and the Turntable, you know these have been long term projects.

The turntable rotating beacon comes on whenever the turntable is in motion.

Then stove fire simulation inside the hut is visible through the door. It’s managed by a little PWM code that will the subject of an upcoming post.

The parking lot side of the Roundhouse has been enhanced with Rix power poles and some EZLINE power cables (which comes in two thicknesses and several colors. I use fine, and chose green–old copper–for its visibility). I fabricated a simple power connection and breaker box for the roundhouse out of a piece of styrene and a brass rod, and an EZLINE cable.

A Woodland Scenics light pole casts a pleasant white-yellow light over the parking lot in night mode. Figures, such as the worker (a Woodland Scenics prepainted figure) at the turntable end of the parking lot breath life into a scene.

Having gone to all the trouble to light the Roundhouse, I’ve started populating the space with some appropriate gear and figures.

A view of the lit Roundhouse interior.

Red Bluffs Yard

The Red Bluffs Yard area has its first structure — a fully lit Yard Office — plus a pickup truck with lighting passing by on the adjacent road.

The Red Bluffs Yard Office is fully lit for night operations. The Woodland Scenics light pole works just fine with my Duino Nodes controlled by an Arduino; treat it like any other 20 mA LED. The truck tailights in the background are from LEDS placed in the rear wheel wells, with the light allowed through tiny holes in the fenders.

Its amazing what a couple of SMD LED headlights can do for a really basic pot metal pickup truck kit from Micro Engineering.

The first of three planned scratch built Signal Bridges has been erected to control one of the approaches to the yard interchange.

And, finally, here is the underside, which is rapidly filling with gear supporting the layout above. This module, with its yard, multiple main tracks and turntable is one of the most electronically “dense” parts of the layout plan, to be exceeded only by the city scene planned for the upper level — that is going to be quite a project and I can hardly wait to finish the lower level and get started on the top!.

The underside of this module is rapidly filling with gear. Obviously overhead soldering is not an issue since I can put the module on its side. That said, I rely primarily on screw terminals and crimped fittings for connections.

PWM Drivers for Turnouts and Other Uses

Pulse Width Modulation (PWM) is used to output a timed pulse, where the output is on only part of the time. The width of the pulses — the percentage of time the pulse in the on state — is used to control external devices like servos or to vary the brightness of an LED.

Some, but not all, Arduino digital outputs are hardware PWM capable. Some of the PWM pins are SPI pins and the two serial pins, leaving only 5 or 6 PWM pins available for unrestricted use depending on the board model. If you want to make extensive use of PWM, that just won’t cut it.

PWM can also be synthesized with timed interrupts on any pin, which is how the servo library works and why it does not require you to attach to PWM pins. Unlike hardware PWM pins, PWM synthesized with interrupts represents a hidden load on your board that can affect the performance of your sketch.

External PWM Boards or “Drivers”

External PWM drivers allow  you to greatly expand the number of PWM devices a single Arduino can manage. PWM is used extensively in robotics, so PWM drivers are fairly ubiquitous and inexpensive. Aside from expanding the number of PWM devices you can control, PWM drivers allow you to off-load all of the PWM overhead and timing routines to the external device, freeing your Arduino for other tasks.

I decided to try Adafruit 16-Channel 12-bit PWM/Servo Driver for servo control and a couple of lighting applications on this module. Adafruit also sells a similar device in shield form.

Adafruit 16-Channel 12-bit PWM/Servo Driver, assembled with original terminal block (blue) that did not hold up to use. I eventually soldered leads to the underside of the board.

I chose the independent board rather than the shield because it has a number of advantages, not least of which it is chain-able with up to 61 additional boards, for a total 992 PWM outputs. A single chain of these can handle the servo needs of most club and museum sized layouts! A more modest layout could use these for both turnout servos and all lights and lighting effects, effectively centralizing and simplifying control of all connected devices. It uses the shared I2C interface for fast communication without using any regular pins on your Arduino. For more details, and a tutorial, see the Adafruit product page.

Assembling the board was straight forward, though there are a lot of pins to solder. The terminal block in the center provides independent power for the servo outputs (V+ center pin on outputs) per standard servo wiring; independent power is required by servos because of their substantial current draw. LED’s and other devices that draw their power from the PWM signal itself will not use the independent power.  Be warned: the terminal block Adafruit supplies is poor quality—substitute a better quality part or solder power leads directly to the board. The headers on the sides are for input and output, transferring both data and power to subsequent boards in a chain.

Adafruit 12 bit 16 Channel PWM Driver installed and connected to servos and lighting.

Connecting servos is just a matter of having a male->female servo extension the right size, or combining multiple extensions for longer runs. Any robotics supply store should have an assortment of extensions; as does Amazon. I have three different sizes to work with, which has worked well so far.

On the board positions 0 through 8 (1st 2 banks of four, plus the first pin of bank 3) are attached to the 9 turnout servos. Positions 9 and 10 are for headlights and taillights on the pickup truck. Using PWM I can have the headlights go between low beam and high beam, or have the taillights brighten as if the brakes have been applied. I have some thoughts about an animated animal crossing in front of the truck from time to time….

Using Adafruit’s PWM Driver Software

Adafruit’s software library for this device is available from their GitHub site. Using the software you create an object that you then use to control the board outputs:

Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

Creating the Adafruit_PWMServoDriver object without arguments uses the base SPI address to access the board; any different address has to be specified as an argument (and the appropriate jumpers on the board have to be closed). With multiple boards, you create a pwm object for each board using its unique SPI address.

From there, the PWM pulse is set on any output by calling the setPWM() member function:

pwm.setPWM(pin, on, off);

where pin is the board output (a number between 0 and 15), on sets the point in the cycle when the signal goes from low to high (usually 0, the beginning of the cycle, but it can be another value) and 0ff is a number between 0  and 4095 setting the point in the cycle when the signal transitions from high to low.

With the Adafruit driver board you do not use degrees to set a servo’s position. Instead we use timing “tick” values that control the signal transitions from low to high and back. There are 4096 “ticks” (12 bits of resolution) during each cycle. That turns out to be a good thing. For servos, the correct off tick values (assuming the on tick is 0) range from about 150 (the minimum or 0 degree position) to 600 (maximum position, 180 degrees).

Directly setting the cycle through ticks at 12 bits of resolution confers highly granular control and extra smooth servo motion.  Using degrees for position, as the standard servo library does, results in jerkier motion since a degree represents a lower resolution–between 8 and 9 bits–than the 12 bit resolution of the Adafruit board. For LEDS and other lighting, you can vary brightness from off to full on in 4096 steps, allowing fine control of lighting effects.

If you ask me, the smooth motion you can achieve with this board makes its $14.95 price more than worthwhile.

The only difference in your code between working with the standard servo library and the Adafruit driver, is in the object and member function you use to cause the servo to move. Every other aspect of your code and logic should remain the same.

What’s Next?

More coding, and I promise I won’t make you wait long. In the next installment I’m going to introduce you to simplified Object Oriented Programming (OOP) in C++ with the Arduino IDE. I’ll demonstrate a different way to code that, I think, improves several aspects of working with multiple turnouts, and makes the intent and flow of your code easier to understand and maintain. We’ve done it procedurally; we are going to take what we’ve learned and create some OOP code to do the work using either the Adafruit driver or the standard servo driver (Hint: we’ll use a compiler directive to select which driver gets implemented, making the object itself agnostic on the issue and universally usable around the layout).

Until then, happy railroading!

Adding a Turntable to the L&NC, Part 2

The Roundhouse / Turntable complex at the Red Bluffs Yard is the focal point of the lower level of the L&NC and one of the more complex projects planned for the layout. In the first installment  (which is also step 4 of the build out of Module 1, lower level) I wrote about how I built the pit and bridge base, and showed the mechanism I developed for the turntable using Actobotics robotics gear.  In this installment, step 5 ( Links to step 1, steps 2 & 3) of this module build out, we’ll take a look at the buildup around the turntable, adding track and integrating it into the scene.  I’ll also talk about how I completed and wired the bridge. Along the way I took the time to install basic scenery elements while I have free access to this section of the layout.

Step 5

Finishing the Pit

The first task after installing and leveling the turntable pit was to create a rim and cover the rough opening for the  pit. After looking at a lot of pictures of prototype turntables I concluded that the rim needed to be around 4 or 5 scale feet wide. Rather than try to cut a circle out of styrene, or something like that, I elected to use a strip of cork roadbed. With the beveled edge against pit wall, and the square edge forming the outer edge of the rim, the look seemed about right.

The flexibility of n scale cork roadbed made it the perfect material for rimming the turntable pit.

The flexibility of n scale cork roadbed made it the perfect material for rimming the turntable pit.

One thing I found out in my research was that track rails are typically attached directly to the rim material (usually concrete) without ties. I decided not to model it that way because I just don’t want to get bogged down with gauging problems. So I elected to mount the ties to the rim so that they will keep the track in gauge.

Its not prototypical, but that’s OK with me because this is one of those places were functional reliability has to win out over prototypical niceties.  As you can see in the picture below, I weaved the ties of the adjoining tracks between each other to achieve the correct track placement along the rim where it meets the bridge. Preliminary testing established that I’m getting good alignment and smooth wheel transits across the gap.

Track from the Roundhouse meets the turntable.

Track from the Roundhouse meets the turntable. Ballasting is in progress so there are bits ballast everywhere at the moment!

I painted the rim concrete to match the rest of the pit.  The texture of the roadbed material is a little rougher than I anticipated. A second coat of paint smoothed it out more and left me with a surface that is a little worn from the effects of time and weather.  I’m pleased with the effect; a perfectly smooth surface just wouldn’t be right.

Finishing the Bridge

In addition to the powered track that also serves as a reversing section, the turntable bridge has an operators hut containing a warming stove with a red LED for creating a hot coals effect. The central arch–which prototypically was often a rotating connection point for the incoming power line to run the turntable–is outfitted with a simulated rotating beacon that will run whenever the turntable is in operation. Not even remotely prototypical, this little enhancement is just a way to animate and make the turntable even more interesting.  I did say at the outset of this project that I was going to throw in animations at every opportunity!

I started the deck by creating a base frame to fit over the bridge and hold a piece of flextrack (I’m doing this layout in Peco code 80 gear).

Bridge deck base frame.

Bridge deck base frame. The track has not been trimmed to its final length yet.

Starting with the base frame, I continued adding cross-members until there was one in each space between ties. Then I decked it with .030 x .080 styrene “planks” cut to various lengths from scale 8′ to scale 32′, creating a plausible planking effect..

The bridge deck before painting.

The bridge deck before painting.

The central arch is fabricated from .080 square tubing. I added etched brass X-bracing in a scale 18″ size so that it would resemble beams fabricated from plates and X-braces. I thought about trying to fabricate brace & plate beams, but felt it would be a little too difficult to pull off and make strong enough for practical use.

The rotating beacon at the top of the arch is fabricated from three red micro SMD LEDS arranged in a triangle. The magnet wires (1 common anode and 3 cathodes) are connected to an incredibly small rotating beacon simulator board that I purchased from Ngineering.com. The have a nice collection of simulator boards geared to model railroading, with everything sized for N scale (these boards will work in any scale, so don’t be deterred if you don’t do N).

The Ngineering rotating beacon simulator board with leads attached.

The Ngineering rotating beacon simulator board with leads attached.

Actually I bought 2 because I ended up screwing up one of the outputs on the first one. These boards are smaller than a dime and soldering wires to them is tricky. On my second attempt I soldered short 30 gauge solid wire leads to the board (easier than soldering magnet wire), then soldered the 40 gauge magnet wire to the leads.

To answer the obvious quesiton, I could very well have done the rotating beacon effect with an Arduino.  However, this little board is particularly good at that job, and I don’t have to use 3 PWM pins (plus the timing sensitive programming) to do the job.  I can run this effect from a single connection on a Duino Node, simply turning it on when the bridge moves and off when it stops at its intended destination.  This is good example of how one has to balance all the trade-offs when designing a system based on Arduino technology. Sometimes an external utility board gets you to the right place more efficiently than doing it from scatch.

Base and walls of the hut, and the stove.

Base and walls of the hut, and the stove.

The operator hut is made from a white metal “trackside shanty” kit by Stewart Products. I decided that the hut needed a little stove for heating, to go with the smoke jack provided by the kit. So I fabricated one from a piece of brass tubing and a styrene circle for a top. I cut an opening in the brass to serve as the front opening.  A red led mounted in the bottom of the tube (not shown) will be used to create a fire effect that you will just barely see through the open door of the hut. I’ll produce the effect with PWM on an Arduino board instead of a dedicated simulator. So the turntable bridge will have two different light animations.

With all the pieces assembled, the wiring in and everything painted, it was time to connect all the wires to the leads from the spinner and attach the deck assembly to the bridge base. If you look carefully you’ll see a black object to the right of the center — that is the beacon simulator in protective heat shrink tubing.

Attaching the deck assembly to the bridge base.

Attaching the deck assembly to the bridge base.

Are those fishing weights attached to the underside of the deck? You guessed it! The white metal hut is rather heavy (relative to the weight of the styrene); the weights are needed to balance the bridge. The white object between the girders on the left is a nylon screw with a rare earth magnet (Neodymium, available from K & J Magnetics) glued to its head, screwed into a nylon nut attached to the bridge. That is for the position sensor reed switches I’ve previously described.

The turntable fully assembled.

The turntable fully assembled.

Scenery

In addition to finishing the turntable I am doing as much scenicking as possible while I have this module on its own on a work table. As I am doing this I am reaping a bonus from my modular design: the ability to take a module and place it on a work table for 360 degree access at chair height.

I'm using CadRail's layers to record information. Here I've recorded feeder positions (in red) and turnout servo positioning data.

Module 1, Lower Level

 

Referring to the drawing of this part of the layout above, I decided to add a small mountain in the space between the yard at the top and the  two legs of the reversing loop at the bottom.  This creates a view block that isolates the yard into its own little world.

I also decided to create a couple of roads using Woodland Scenic’s Road System paving tape and Smooth-It pavement material. The system works pretty well. I do recommend viewing their video tutorials for instruction in using the system, which you will find on the product pages.

Creating an access road at the Red Bluffs Yard.

Creating an access road at the Red Bluffs Yard.

After removing the forming tape, you are left with this:

The road at Red Bluffs with forming tape removed.

The road at Red Bluffs with forming tape removed.

You’ll see that the road includes a driveway and parking lot at the top of the picture, and another driveway at the bottom that will lead to a gravel parking lot. These are provisions for future structures I have planned –a multi-unit rooming house for railroad workers at the top and a yard office at the bottom. I also created a road on the opposite side of the module, running between the legs of he reversing loop as an access road to the roundhouse / turntable complex.  I figure the employees need some way to get to and from work!

The mountain was made from several layers of foam insulation glued together then carved to a rough shape. I glued the foam shape to the layout, then covered the whole thing in plaster cloth. Then I selected some rock molds and cast a few rocks. After gluing the rocks to the mountain  (Attach rocks with wet plaster? Forgetaboutit! Liquid Nails for Projects makes attaching hydrocal rocks to another surface a snap, with its strong tack and immediate hold), I filled holes and blended the rocks into the terrain with Sculptamold. I painted everything except the rocks the medium tan I’m using as a base color, then painted the rocks themselves with a combination of iron oxide and earth tones. I glued down some earth blend and other ground foams — and, voilà, the red bluffs were born.

The Red Bluffs

The Red Bluffs

What’s Next?

More scenicking, of course.  But it is getting to be time to go underneath the module again and install more of the electronics, including controller hardware for the 9 turnout servos and the controller package for the turntable / roundhouse.

Until then, happy railroading!

Running a Small Layout with an Uno

Arduino Uno R3

Arduino Uno R3

A reader on another thread had questions about running multiple turnouts on a small layout with an Uno. Primarily he wants to control turnouts with a control panel and feedback indicators.  I thought that his needs are pretty typical for small layouts, and would be a good example for others planning and building on a similar scale.

So this post is bottom-up exercise in planning and implementing single UNO control on a small layout. I hope it will be helpful in planning and building your layout.

The Requirements

The layout has 5 turnouts that will be controlled with push buttons. Control is toggle-style: each button push causes the turnout to toggle between positions. Turnouts are run by micro servos. The control panel will have a layout map with turnout push buttons and LED position indicators.

First Decisions

The UNO is the first board many of us encounter and is certainly up to the task of managing 5 turnouts and a control panel, with capacity to spare. There are other Arduino boards suitable for model railroading use; but the UNO is cost-effective and easy to work with.

That said, the issue you have to contend with eventually is the number of connections required to support all the devices and LEDS that will be attached to the microcontroller.

Arduino boards provide three different types of connections/pins:

  • Digital: digital pins are basic on/off binary connections. In output mode they are either fully on (emitting 5 volts, with a max current of 40 mA) or off. In input mode they read the incoming current as either HIGH (on) or LOW (off). When used as inputs, digital pins may need pull-up or pull-down resistors so that they will function correctly.
  • Digital PWM: some, but not all, digital pins are also capable of PWM – pulse width modulation.  The output of a PWM pin, if not fully on or off, is a series of pulses that cause the output to to on a percentage of the time.  The pulses are used to control servos and other PWM devices. PWM with LEDS lets you vary their brightness between 0 and 100%, supporting a variety of interesting lighting effects.
  • Analog: Analog pins are primarily used to read sensors that produce a variable output. Pin inputs are fed to the on-board ADC (analog-to-digital converter) for conversion to a number between 0 and 1024. Current and temperature sensors are example of analog devices read through analog pins / ADC. What you may not know about analog pins is that they can also be used as basic digital pins.

It is essential in early planning to determine all the devices to be connected to the microcontroller and the type of connection each requires to determine what connection issues you will need to resolve. In some cases, going to the UNO’s bigger cousin, the MEGA, will solve connection limits.  But even the MEGA has limits. In some cases it makes sense to use pin-multiplying techniques using external chips to drive banks of LEDS, servos or other devices, even when you otherwise have enough pins.

A Connection Plan

The UNO has 14 digital connections, numbered 0 to 13, of which 6 (pins 3, 5, 6, 9, 10, and 11 ) are PWM. It also has 6 analog connections that can be used as digital connections with digitalRead() and digitalWrite() when referenced in the sketch as A0 through A5. That is a grand total of 20 digital pins, of which 6 are PWM.

Of those, two pins are generally off limits on an UNO: digital pins 0 and 1. They are Serial RX and TX respectively, and should be avoided for other uses on any UNO where you expect to use the USB interface — that would be most of the time. On boards without the built-in USB, pins 0 and 1 are fair game.

For five servos we need five digital pins. Even though PWM is used to control servos, the Arduino servo library creates the necessary pulses on any digital pin. However, using the library disables PWM functionality on pins 9 & 10, so some of the UNO’s native PWM capacity is sacrificed in any case.

For the five turnout control buttons we need five basic digital pins. For the control panel indicators, assuming one LED for each leg of each turnout, we need 10 basic digital pins.

That means we need 20 connections; but with pins 0 & 1 reserved for the USB interface, we’re short 2 connections. Many would want to use bi-color red/green LEDS so the state of each leg is continuously shown. That would require 10 additional basic digital connections.

Need Connections? No Problem!

That’s OK. Its exactly what I expected to happen when I started in on this exercise. Both inputs and outputs can be multiplied with external chips and boards; multiplying the basic digital outputs is far and away the easiest to implement, because the circuits are simple and the compiler includes native software support without add-on libraries.

I would use shift registers to control all the control panel indicators. That reduces the connection load on the UNO to just 3 connections for all LED indicators, no matter how many you end up with. With that, and the 10 pins needed to read the buttons and control the servos, the total digital pins requirement is 13. That leaves 5 available pins, one analog and up to three digital PWM, for other uses.

There is a great tutorial on controlling LEDs with shift registers, and chaining multiple registers together, on the Arduino website. That tutorial is mandatory if you are unfamiliar with shift registers; the circuit(s) shown are what you will be using for control panel LED indicators. The balance of this post assumes the basic knowledge contained in that tutorial.

Build A Control Board

Use a shift register chain to run your panel indicators. I use a TI 74HC595 chips that I buy from DigiKey. At less than $.50 each in lots of 10, they are a bargain. $5.00 worth of chips supports 80 outputs. Its the cheapest way I know of to extend the capabilities of an Arduino and run a lot of low current devices.

Decide how many shift registers you need — the 74HC595 has 8 outputs — and create a board based on the tutorial circuits to hold the chips and provide connection points for your LEDS. A single LED for each leg of each turnout (to show which leg is open to traffic) will need 10 connections—use two shift registers (use the two-chip circuit in the tutorial). Add a third chip (after the tutorial you will know how to do that) and your connection count rises to 24, enough to support red/green bi-color LEDS on each turnout leg on the panel. With 4 connections left, who knows what else you might light up?

Each push button will need a 10kΩ pull-down resistor connecting its pin to ground.  The purpose of the pull-down resistor is to drain stray current and keep the pin LOW unless the button is pushed and full current flow is applied.  See the diagram below. The resistor should be placed as close to the pin as possible.

Servo Control by Button

Basic Servo Control by Button

Power Issues

While you can run one or two servos off the power supplied by the UNO’s +5 volt pin, more servos than that would exceed the board’s power handling capabilities. Accordingly, you will need to supply power to the servos from a separate power source. VERY IMPORTANT: the ground for the servo power source must be tied to UNO ground or the servos will not work correctly.

One Sketch To Run it All

Alright. The control panel is built and wired; the servos are installed (see this post for my latest methods) and connected to power and the UNO. What you need now is a sketch to run the control panel and the servos.

Here is a demonstration sketch to get you started:

//////////////////////////////////////////
//
// Small Layout turnout control
// Demonstration Sketch
//
//////////////////////////////////////////

#include <Servo.h> // include the Servo library

////////////////////////////////////////
//
// Definitions
//
////////////////////////////////////////

////////////////////////////////////////
// Basic parameters; adjust for your actual setup
#define NUMBER_OF_TURNOUTS 5
#define NUMBER_OF_SHIFT_REGISTERS 3
#define STEP_DELAY 70  // servo movement step delay, in milliseconds
///////////////////////////////////////

///////////////////////////////////////
// Data Structures
///////////////////////////////////////

//////////////////////////////////////
// TURNOUT_DEF holds all configuration
// information about turnouts and panel LEDS
//////////////////////////////////////
typedef struct TURNOUT_DEF {
  uint8_t button_pin; // Digital or analog pin for the button associated with this turnout
  uint8_t servo_pin; // Digital pin for the servo associated with this turnout
  int pos_main; // servo position for the MAIN leg, in degrees
  int pos_div; // servo position for the DIVERGENT leg, in degrees
  int panel_LED_main_green; // The position(s)of panel LEDS in the shift register chain
  int panel_LED_main_red; // Example assumes a bi-color (red/green) LED for each turnout leg
  int panel_LED_div_green; // modify these elements to reflect the actual LEDS you are using
  int panel_LED_div_red;
};

/////////////////////////////////////
// TURNOUT_DATA is wrapper structure holding
// both configuration and runtime data for turnout operation
/////////////////////////////////////
typedef struct TURNOUT_DATA {
  TURNOUT_DEF data; // configuration
  bool is_moving;
  byte alignment;
  int pos_now;
  int target_pos;
  unsigned long last_move;
};

// Alignment state values
#define ALIGN_NONE 0
#define ALIGN_MAIN  1
#define ALIGN_DIVERGENT 2


// pin ids for shift register chain controlling panel LEDS
#define LATCH_PIN 7
#define CLOCK_PIN 8
#define DATA_PIN 9

//////////////////////////////////////////
//
// Global variables
//
//////////////////////////////////////////

//////////////////////////////////////////
// TURNOUT_DATA Array
// * A0, A1, etc refer to analog pins which are used for buttons in this example
// * Replace pos_main (93) and pos_div (117) with real values for each turnout
// * LEDS are identified by their output position in the shift register chain;
// the identifier is a number between 0 and (NUMBER_OF_SHIFT_REGISTERS * 8) - 1. 
// Example assumes LEDS are connected to shift register outputs sequentially 
// from the first output of first register. You can connect LEDS to any output in
// any order; just set the identifiers accordingly.
//
// Only the TURNOUT_DEF part of the TURNOUT_DATA structure has to be initialized here; 
// The remaining elements are managed internally and are initialized automatically
//////////////////////////////////////////

TURNOUT_DATA turnouts[NUMBER_OF_TURNOUTS] = {
  {{A0, 2, 93, 117, 0, 1, 2, 3}},
  {{A1, 3, 93, 117, 4, 5, 6, 7}},
  {{A2, 4, 93, 117, 8, 9, 10, 11}},
  {{A3, 5, 93, 117, 12, 13, 14, 15}},
  {{A4, 6, 93, 117, 16, 17, 18, 19}}
};

// servo objects
Servo servos[NUMBER_OF_TURNOUTS];

// array to hold shift register state bytes
byte panel_LEDS[NUMBER_OF_SHIFT_REGISTERS];

void setup() 
{
  // Setup pins for shift register chain
  pinMode(LATCH_PIN, OUTPUT);
  pinMode(CLOCK_PIN, OUTPUT);
  pinMode(DATA_PIN, OUTPUT);
    
  // initialize each turnout 
  for(int i = 0; i < NUMBER_OF_TURNOUTS; i++){
    // attach the servo
    servos[i].attach(turnouts[i].data.servo_pin);
    // set the pin mode for the button pin
    pinMode(turnouts[i].data.button_pin, INPUT);
    // test and position the turnout by moving
    // to divergent then to main positions
    servos[i].write(turnouts[i].data.pos_div);
    turnouts[i].pos_now = turnouts[i].data.pos_div;
    setTurnout(i, ALIGN_MAIN);
    }
} // end of setup

void loop() 
{ 
  // get elapsed milliseconds at loop start
  unsigned long currentMillis = millis();

  // loop through the turnouts array
  for(int i = 0; i < NUMBER_OF_TURNOUTS; i++){
    if (turnouts[i].is_moving) {
      // if sufficient time has elapsed since the last move
      if ( (currentMillis - turnouts[i].last_move) >= STEP_DELAY ) {
        // move the turnout one degree
        turnouts[i].last_move = currentMillis;
        if (turnouts[i].pos_now < turnouts[i].target_pos) { // if the new angle is higher
          servos[i].write(++turnouts[i].pos_now);
        } else {  // otherwise the new angle is equal or lower
          if (turnouts[i].pos_now != turnouts[i].target_pos) { // not already at destination
            servos[i].write(--turnouts[i].pos_now);
          }
        }
      }
      // if target position reached, stop turnout motion
      if (turnouts[i].pos_now == turnouts[i].target_pos) {
        turnouts[i].is_moving = false;
        turnouts[i].last_move = 0;
        setIndicators(i);
      }
    } else {
      // if a turnout is NOT in motion, check to see if its button is pressed
      int button_state = digitalRead(turnouts[i].data.button_pin);
      if(button_state == HIGH){
        // toggle position
        if(turnouts[i].alignment == ALIGN_MAIN){
          setTurnout(i, ALIGN_DIVERGENT);
        } else {
          setTurnout(i, ALIGN_MAIN);
        }
      }
    }
  }
}// end of main loop

////////////////////////////////////////////////////////////////
// Supporting Functions
////////////////////////////////////////////////////////////////

void setTurnout(int id, int align){
    // Set indicators to show turnout in motion
    turnouts[id].alignment = ALIGN_NONE;
    setIndicators(id);
    // Set values to trigger motion on next loop iteration
    switch(align){
        case ALIGN_MAIN:
          turnouts[id].is_moving = true;
          turnouts[id].last_move = 0;
          turnouts[id].target_pos = turnouts[id].data.pos_main;
          turnouts[id].alignment = ALIGN_MAIN;
          break;
        case ALIGN_DIVERGENT:
          turnouts[id].is_moving = true;
          turnouts[id].last_move = 0;
          turnouts[id].target_pos = turnouts[id].data.pos_div;
          turnouts[id].alignment = ALIGN_DIVERGENT;
          break;
      }
}

void setIndicators(int id){
  switch(turnouts[id].alignment){
    case ALIGN_NONE: // means the turnout is in motion and not aligned
      panelWrite(turnouts[id].data.panel_LED_main_red, HIGH);
      panelWrite(turnouts[id].data.panel_LED_main_green, LOW);
      panelWrite(turnouts[id].data.panel_LED_div_red, HIGH);
      panelWrite(turnouts[id].data.panel_LED_div_green, LOW);
      break;
    case ALIGN_MAIN:
      panelWrite(turnouts[id].data.panel_LED_div_green, LOW);
      panelWrite(turnouts[id].data.panel_LED_div_red, HIGH);
      panelWrite(turnouts[id].data.panel_LED_main_green, HIGH);
      panelWrite(turnouts[id].data.panel_LED_main_red, LOW);
      break;
    case ALIGN_DIVERGENT:
      panelWrite(turnouts[id].data.panel_LED_div_green, HIGH);
      panelWrite(turnouts[id].data.panel_LED_div_red, LOW);
      panelWrite(turnouts[id].data.panel_LED_main_green, LOW);
      panelWrite(turnouts[id].data.panel_LED_main_red, HIGH);
      break;
  }
}
/////////////////////////////////////////////////
// Shift Register Functions
/////////////////////////////////////////////////
void panelWrite(int id, byte state) {
  int reg = floor(id / 8);
  int pos = id % 8;
  bitWrite(panel_LEDS[reg], pos, state);
  panelRefresh();
}

void panelRefresh(){
  // Prepare to shift by turning off the output
  digitalWrite(LATCH_PIN, LOW);
  // shift all bits out in MSB (most significant bit first) order
  for(int i = (NUMBER_OF_SHIFT_REGISTERS - 1); i>=0; i--) {
    // shift out the bits
    shiftOut(DATA_PIN, CLOCK_PIN, MSBFIRST, panel_LEDS[i]);
  }
  // turn on the output to activate
  digitalWrite(LATCH_PIN, HIGH);
}

The sketch compiles into a compact package leaving plenty of memory and resources for additional functionality.

The main loop is built around a simple multitasking model, allowing you to control task timing and balance multiple competing tasks.  In this case, the main benefit of this methodology is control of the movement rate of turnout servos. On my test loop this methodology allows block occupancy detection to work in the background along with signal logic.

UP995 at Signal 34. Dual Searchlight Signals, Scratch Made with BLMA Signal Heads.

UP995 at Signals 3 & 4 on the Test Loop. Dual Searchlight Signals, Scratch Made with BLMA Signal Heads.

Troubleshooting

If you build the circuits accurately, everything should work out of the box (as it were). I am an obsessive tester — so I test things at critical stages as I build them.  Build and test your shift register circuits on a breadboard first, before soldering everything to a prototyping board.

To test the sketch I set up a simulation on a breadboard.

To test the sketch for this post I set up a 3 servo simulation on a breadboard.

Getting the connections to the UNO correct is key. If the LEDs don’t light at all, check all three connections, plus power connections; LEDS are polarized, so make sure the anodes are connected to incoming power and the cathodes to ground. Tracing power flow with a multi-tester should help you find problem areas quickly.

If your LEDs light but alternately flash odd/even, you probably reversed the LATCH_PIN and CLOCK_PIN connections.

For 3 or more servos, you must have an independent power supply to power them. BE SURE TO CONNECT GROUND FROM THE SERVO POWER SUPPLY TO ARDUINO GROUND.

Do Something with Unused Outputs

Old style hard wiring, without the help of a microcontroller, is a messy business at best, which tends to limit what you can do. DCC can help bridge the gap, but layout control is something of an afterthought for DCC (it was designed for locomotive control only) and is, frankly, awkward to use (my opinion; your mileage may vary).

To get the kind of functionality we have here without Arduinos — turnout control with a synchronous control panel — it would have to be hard wired. Or you could connect a full computer and run JMRI; that would require DCC (plus stationary decoders for the turnouts and a USB->DCC interface) to work . You would have to use stall-motor type turnout motors or add microcontrollers (Peco now sells a “smart” turnout system using servos and custom controllers) to interface with servo motors. So if you want to use servos instead of stall-motors, you can go Peco or do it the Arduino way from the start. As much as I appreciate Peco’s efforts here, the openness of the Arduino platform is a big part of what makes it useful and cost-effective.

Adding another function to a small layout — lets say a signal to protect a turnout — is a matter of connecting the signal leads to unused outlets and writing some code to run it.  If you’ve gotten this far, you’ll spend far more time thinking about exactly how the signal should run in conjunction with the turnout it is protecting, than you will connecting the device and adding code to the sketch.  Once you get into this way to doing things, I guarantee you’ll never look back.

So what will it be? Signals?  A fire simulation (using PWM and LEDS)? A lighted structure? Let your imagination run wild!


UPDATE

I starting working with shift registers a while back.  They are so effective my habit is to always use shift registers with LEDs, such as for signals, structure lighting and control panel applications.  The habit is so ingrained that I forget to mention the other important reason for using them: power management.

The power handling capability of an UNO is limited to 40 mA per pin and 400 mA for the entire board. LEDs typically draw between 20 and 30 mA.  So if you are directly powering 20 LEDs from an UNO, you are exceeding its power handling capacity and will burn out the board.

In the example given in the post, no more than half the LEDs well be lit at any one time so we are unlikely to exceed the 400 mA limit overall. A few more lit LEDS, though, would put it over the top.  Shift registers duck the problem altogether because each register is powered—and supplies power to connected devices—independently.  Other than the total load on your power supply, adding devices/lights to shift registers or even adding additional registers, puts no significant power load on the UNO.

Above I mentioned that an independent power supply is needed to run the servos.  From a “best practices” perspective, one should always power external devices with an independent power supply. Arduino’s current handling limits are tight; always using external power supplies avoids that problem.


UPDATE

Several readers asked if I have a fritzing image of the 3 servo demo.  I did not, but I put one together for those who might find this helpful.

3 Servo Demo

This circuit is intended to work with the above sketch, with the turnouts variable shortened to 3 elements instead of 5:

TURNOUT_DATA turnouts[NUMBER_OF_TURNOUTS] = {
  {{A0, 2, 93, 117, 0, 1, 2, 3}},
  {{A1, 3, 93, 117, 4, 5, 6, 7}},
  {{A2, 4, 93, 117, 8, 9, 10, 11}}
};

Always cross check all connections on a circuit like this against appropriate data sheets before powering it up for the first time! Be sure to connect the ground of your Arduino to the ground of your external power supply.

Wiring the L&NC — Adding Servos

This it the second installment in a series (Part 1) about the build out of Module 1, lower level of the L&NC. This series covers all the basic steps I’m following to install all wiring, electronics and mechanical objects throughout the layout, so in subsequent phases of this project I can focus on the unique aspects of other modules. Step 1 was to install the basic wiring trunks and connection points, create track power distribution nodes then connect track feeders to the nodes.

Step 2

I tested the track with one of my most challenging locomotives—a Broadway Limited EMD E8A DCC with Sound. I say “challenging” because it has two 3-axle trucks, a long wheelbase and no big capacitors to buffer track power, making it susceptible to derailment or operational problems with faulty track.  If this loco can run a stretch of track problem-free, it’s good track!  Naturally I found and fixed a few (cough …. ) places where there were problems.

Correcting track problems for flawless running.

Correcting track problems for flawless running.

After tinkering with the problem zones, I realized that the “course of least resistance” was to rip out and re-lay a few short strips of track. The caulk adhesive track laying method makes this a piece of cake: after cutting the rails, run a long bladed knife under the track section you want to remove and its free in seconds. The ease of fixes really adds incentive to be fussy at this stage and get it right. I had everything in good order in a couple of hours including drying time for fresh caulk adhesive.

Step 3

The next step is to mount the servos running the 9 turnouts on this level. Installing them now is the best way to ensure they have the space they need for normal operation and maintenance.

test loop servo 1 in place

Servo mount on the Test Loop.

I’ve previously done a basic demo of the mounting method I used on the Test Loop. I chose that particular mounting method because it simplified the connection between the servo and the rod connected to the turnout; the rod fits easily but snugly through the hole in the horn. In this mounting method the base plate of the mount provides the fulcrum or pivot point for the rod.

Turnout operation on the Test Loop continues to be 100% reliable. The only issue with that mounting method is that noise is transmitted to the layout through the mount, so servo operation is noisier than it should be.

A New Low Noise, Low Profile Servo Mount

In addition to noise control, the equipment space beneath the layout level is about 1 3/4 deep, the width of a 1″ x 2″ frame member. For both protection and aesthetics, I need all equipment to fit inside that space. The old servo mounting method requires more space than that, and would stick out below the edge of the frame.

The solution is to mount the servo on its side, allowing the horn to rock a rod back and forth setting the turnout points. Several obvious ways to do that came to mind.  But I also wanted to make sure that alignment of the servo is easy and foolproof.

Layout Prep

I drilled holes for the turnout rods when I laid the track. To make installation and alignment of the servo easy, I  drilled the holes so that the rod would be in the 90 degree position (perpendicular to the plywood base) with the points aligned one direction or the other. I tried to keep the holes through the plywood small to serve as fulcrums  (mostly succeeded), then widened the holes in the foam and roadbed beneath the track so the rod can swing between the two positions of the points.

I inserted a 3″ rod cut from 1/16″ music wire (you need a hard wire cutter for this stuff) and made sure the positioning of the rod was correct. The advantage of the music wire is that it can flex without deforming, allowing you to apply pressure to the points.

Fulcrum pad for turnout 5

Fulcrum pad for turnout 5

That said, 1/16″ music wire I’m using is fairly stiff in the short lengths needed here. It is stiffer than the wire typically use with stall motor turnouts, stiff enough that it easily overcomes resistance from the built in springs in the Peco turnouts I’m using on this layout. Many people recommend removing the positioning springs in Peco and similar turnouts, since they can cause turnout movement to pause while overcoming resistance of the spring. Using 1/16″ music wire the servo is able to move a sprung turnout smoothly. I took a few springs out before I realized it was completely unnecessary.

 

At this point I made sure the rods could move the points properly.  In a few cases, the fulcrum hole was a little too large because of sloppy drilling; the easy solution is to fit a plywood plate with a fulcrum hole in the right diameter over the old one.

Servo Prep

Preparing the servo requires testing and setting it to the 90 degree position. Then with the case on its side, orient the output shaft to either the right or left (which ever you need for a given situation) and install a standard single arm horn pointing up, perpendicular to the case.

The offset shaft allows you to select the right orientation. In either case, 0 degrees is 1/4 turn to the right of center, 180 degrees is 1/4 turn left of center.

The offset shaft allows you to select the right orientation. In either case, 0 degrees is 1/4 turn to the right of center, 180 degrees is 1/4 turn left of center.

Here’s a sketch to test the servo by running it from 0 to 180 degrees (the travel of a typical micro servo), then to the required mid-point position:

#include <Servo.h> 
 
Servo myservo;  // global servo object
int midpoint = 90;  // in degrees
int pin = 6; // control pin

void setup() 
{ 
  int i;
  myservo.attach(pin);
  myservo.write(0);
  delay(1000);
  for(i = 1; i <= 180; i++){
    myservo.write(i);
    delay(50);
    }
  delay(1000);
  for(i = 180; i > midpoint; i--){
    myservo.write(i);
    delay(50);
    }
  delay(1000);
  myservo.write(midpoint);
} 
 
void loop() 
{ 
  
}

Mr. Hot Glue Strikes Again

If only micro servos came with side mounting tabs instead of just the ones on top. They do not. To do a side mount like I’m doing you need only fabricate two parts: 1) a strip of .080″ styrene, cut to about 2″ x .5″ and predrilled with holes at each end to accommodate mounting screws; and 2) a piece of 1/32″ brass wire with a loop (a little over 1/16″ inside diameter), a short straight section (about equal to the thickness of a servo horn) leading to a 90 degree bend and a longer straight section.

These two parts allow you to side mount a micro servo, and connect its horn to a rod.

These two parts allow you to side mount a micro servo, and connect its horn to a rod.

First I remove any labels on the side of the servo that attaches to the mount, then I put a dab of hot glue on the servo and press the styrene strip against it, centering and aligning the strip with the built in fins. Then I put a bead of hot glue down each side of the servo where it joins the mounting strip. Its probably overkill, but I want the servos mounted solidly and resistant to torsional stress.

Micro servo glued to a side mounting strip.

Micro servo glued to a side mounting strip.

The brass wire is threaded through the top hole of the horn, with the long leg aligned along the length of the back side of the horn and the loop parallel to the base. Apply dabs of hot glue to adhere the wire to the horn.

Here you can see how the brass wire is glued to the horn, and the turnout rod is threaded through the loop.

Here you can see how the brass wire is threaded through the top hole glued to the horn, and the turnout rod is threaded through the loop. Note the clearance between the rod and the horn.

Installation

Here a servo has been aligned to the motion of the rod, marked on the plywood.

Here a servo has been aligned to the motion of the rod, marked on the plywood.

First it is necessary to determine the plane along which each rod moves; that will depend on the angle of the turnout relative to the rest of the layout.

With the plane of motion marked and the rod set to its 90 degree position, I slip the rod through the loop glued to the horn and place the servo next to the rod, parallel to the plane of the rod. Placing just a little tension on the rod and maintaining even clearance between the horn and rod, I mark and drill mounting holes for the servo. Sometimes its easiest to do one mounting hole, attach the servo at that hole then—after adjusting positioning—drilling the second hole and completing the mount.

After a test fitting, I remove the servo and apply a strip of 3/4″ Rubber Splicing Electrical Tape (Scotch #2242) to the bottom of the mount to inhibit noise transmission. I remount the servo in its final position.

Servos 1, 2 and 9 mount in their final positions.

Servos 1, 2 and 9 in their final positions.

Problems at Turnout 4

The location for turnout 4's servo.

The location for turnout 4’s servo.

Turnout 4’s rod comes down at an awkward spot, close to a frame cross member, the edge of the layout, the main wiring bundle and three feeder sets. The feeders are the main problem; I should have located them further from the turnout. While moving the feeders is an option, I also realized that the fulcrum hole was too large so I was going to have to put in a new fulcrum plate anyway.

The solution I came up with was to fabricate a mounting plate from a couple of pieces of scrap plywood, that would provide a new fulcrum and cantilever over the feeders. Everything screws down so that it is removable and repairable.

Mounting solution for Turnout 4.

Mounting solution for Turnout 4.

 

Turnout 4 Servo Mounted. The horn swings UP in this photo, so the wire bundle below the servo does not interfere.

Turnout 4 Servo Mounted. The horn swings UP to change the position of the points (as oriented in this photo), so the wire bundle below the servo does not interfere. Its snug but effective.

Gathering Servo Positioning Data

At this point it makes sense to test each servo and determine the positions for each point setting.  Each servo installation is different so each one will have unique settings for turnout positions. The size or “looseness” of the fulcrum hole and the length of the rod are the main factors affect servo positioning

On this module and level it takes approximately 20 – 30 degrees movement of the servo to change the points. Once I determined that, it was easy to calculate initial positions that could then be fine tuned for individual installations.

I'm using CadRail's layers to record information. Here I've recorded feeder positions (in red) and turnout servo positioning data.

I’m using CadRail’s layers to record information. Here I’ve recorded feeder positions (in red; turntable area not yet built) and turnout servo positioning data (green). The two positions are “S”, straight or Mainline; and “D”, divergent.

The goal is to have the points firmly pressed against the rails at each end of their travel, without making the servo work so hard it gets noisy. A light hum while the servo is holding a position is OK; but it should not become a loud buzz and the servo should not feel “buzzy” to the touch. Try moving the turnout manually – you should get resistance to moving the points against the servo, but the flex of the music wire should still be evident. Tinker with this for a while and you’ll start to get a feel for it.

Next step is a big one: install the turntable mechanism, install the Roundhouse base, lay track, and so on. Until then, happy railroading!

 

 

 

Wiring Module 1 of L&NC

After a long pause, I’ve starting in on wiring the L&NC by doing the basic wiring on module 1, lower level (each module has two levels). Module one is the largest of the three modules at 54″ long, and is the intended entry point for all the incoming power and control connections. Everything I do here is intended to set the methods and practices for the remaining modules.

Applying Lessons from the Past

Test Loop wiring. Block sensors were added in Phase 2. Phase 3 signals and lighting in progress.

Test Loop wiring. Block sensors were added in Phase 2. Phase 3 signals and lighting in progress.

My early layouts were primitive from a wiring perspective (and other perspectives…. but lets not dwell on that ….). I never did get into the suitcase connector thing, but the old layouts were wired using a single bus pair connecting to feeders every few feet.  Not much to it, so there was not much to organize. Like many layouts, the wiring was somewhat exposed and disorganized underneath.

While I was experimenting on the Test Loop, the wiring was built up in layers without a master plan.  For example, the power distribution from a central barrier strip was fine at first, but later it became necessary to create secondary distribution points to support various power needs. I ended up with wiring  less than optimally organized. On the plus side, I found that small circuit boards with banks of screw terminals are an excellent way to distribute power to to individual feeders or devices.

The other major lesson from the test loop is that it is a pain in the rail to add a major electronic component after everything else has been wired up. Major components should be sited and accounted for before interconnecting anything.  Components that move—e.g., servos, turntable mechanisms or whatever—get priority to ensure they get the placement and space they need — everything else has to adapt to their needs. In this case I will be installing the servos and the turntable early … but I’m getting ahead of myself again.

Special Issues with the L&NC

The L&NC has to be wired with a different aesthetic given that it is intended to be dissembled, moved and reassembled reliably. I am using the Digitrax Empire Builder DCC system, along with my Arduino-based independent control system and a multi-voltage power system supporting the layout — with power provided by a converted computer power supply. Computer power supplies can furnish 300 or more watts of fully regulated power at 12, 5 and 3.3 volts, perfect for every need other than track power.

L&NC Lower Level, Version 2

L&NC Lower Level

The lower level of module 1 (left-most module in the drawing) is fairly complex to wire because it contains the Red Bluffs Yard and the Roundhouse/Turntable complex. Including the feeders needed for the Roundhouse/Turntable area, 24 track feeders with current sensors have to be managed.

Yikes! That’s a lot of feeders for a 54″ x 27″ layout section! Its because of the yard, Roundhouse and turntable. Each roundhouse bay, the turntable bridge and any adjacent track segments adjoining the turntable all need individual feeders; the turntable is a reversing segment. Then each leg of the yard needs feeders, plus the base feeder for the ladder, to support occupancy detection and reliable operation. The main track loops each have two feeders. It all adds up…

So there is a lot more wiring in the L&NC than might be considered normal, and it has to be secure and well organized.

Step 1

With most track laid (I’m deferring the Roundhouse area until the turntable is installed) and the locations of all feeders and turnouts established, the first step is to place the primary distribution nodes then route, terminate and secure the main power bundle, the track bus and the LOCONET bus.

Connection Panel

Connection Panel

At the far left end of the module I placed a connection panel fabricated from styrene. There are four connections:

 

  1. Main power (4 conductors: 12 volt, 5 volt & 3.3 volt, plus ground);
  2. track power connection (2 conductors: Track A & Track B);
  3. LOCONET RJ12 jack (6 conductors); and
  4. Ethernet RJ45 jack (8 conductors).

 

 

My primary color coding scheme:

  • Black = Ground
  • Yellow = 12 volts DC
  • Red = 5 volts DC
  • Blue = 3.3 volts DC
  • Green = Track A (right-hand rail)
  • Violet = Track B (left-hand rail)

For the two power connections, I’m using Anderson Powerpole 15 Amp connectors to create polarized, color coded connectors. 2 connector and 4 connector brackets secure the receiving connection to the panel. I really love these connectors because they are easy to assemble (provided you invest in the crimper), come in a wide variety of colors, allowing you to assemble plugs and matching receptacles that can only be connected together one way. I get my supplies from Powerwerx.com.

Connection Panel, Inside

Connection Panel, Inside

From the panel, the wires run a few inches to a barrier strip.  Here the power is split – one branch going off to feed other parts of this level, with another branch heading to the upper level.

To supply power to the upper level I installed a short piece of PVC pipe from underneath the module, running up next to the corner post, terminating above the bottom edge of the upper level (when installed) I ran wires from the barrier strip up through the pipe, leaving 8″ or so extra cable extending from the top of the pipe, terminated with Powerpole plugs coded for the two power bundles.

Center Barrier Strip

Center Barrier Strip

To get to other areas of the lower level I ran cables from the first barrier, along the edge of the frame, using screw-in eyelets every 6 – 8 inches to channel the cables.  I terminated the cable run at a strip near the middle of the module, then ran an addition  set of cables from the middle strip to the right hand edge of the module.  Leaving 8 inches of slack, I terminated the cables with Powerpole plugs to be connected to a panel on the adjoining module.

The RJ11 jack has leads that I soldered to a six wire cable, then run that cable along the front edge of the module, opposite the power cables, to the location of a Digitrax UP5 universal panel (attached to the frame pending the addition of fascia), terminating the cable with an RJ11 plug as required to attach to theUP5. I fabricated another cable to run from the UP5 to interconnect bundle at the right side of the module.

Track power distribution block with ACS712 current sensors.

Track power distribution block with ACS712 current sensors.

The Ethernet jack on the panel is one end of a prefabricated cable available from Adafruit Industries. The other end will connect to a small Ethernet switch which will install at a later date. From there I’ll  make custom Ethernet cables (my crimper does both 6 and 8 conductor connectors) to fit where needed. Ethernet wiring will be added after I know the location of the Arduinos it will be supporting. I have an 8 port unit ready for the task.

I set up two track power distribution areas with a current sensor for each block, one on each end of the module. At this point I’m keeping the center area clear pending installation of the turntable. A third distribution area will be setup in that area to service the Roundhouse, turntable, service  and approach tracks.

Wiring phase 1

The big picture: wiring step 1 done

Now that the basic wiring is in, its time — finally! — to test the track installation, and fix what ever problems I find before moving on to the next step.  Until then, happy railroading!

Correcting track problems for flawless running.

Correcting track problems for flawless running.

 

Adding Signals to the Test Loop

Tomar Signals

Tomar Signals

With block occupancy detection running on the test loop, it was time  to start experimenting with signals. Automated signaling is an important part of the plan for the L&NC.

Signaling potentially involves a great deal of wiring. It isn’t particularly difficult when done the Arduino way, but it does force you to deal with common capacity issues that come into play whenever you want to control a lot of lights or other kinds of devices.

I think of signals as the simplest form of animation a layout can and should have. Creating a signaling system is a good starting point for developing more complex automation and animation for the layout.

Initially, I bought a couple of Tomar Industries n scale signals to try out something off-the-shelf. These particular ones are nicely made and fully wired with red and green LEDS. A three aspect (red, yellow, green) version is also available.

With two outputs required to power each signal, it became clear that directly powering an entire signal system from a microcontroller would be impractical because there aren’t enough pins to work with. Further, The Tomar signals turned out be wired in the common anode configuration, which had additional implications. Common anode wiring is not unusual in off-the-shelf accessories.

Current Limitations

Arduino boards have design limitations when it comes to powering and controlling external devices. The amount of current an Arduino can source or sink on any one pin is limited to 40 mA, enough to light a couple of LEDS. The ground pins can sink a maximum of 400 mA. Accordingly, an UNO could power a maximum of 10 pins with no more than two 20 mA LEDS on each. The I/O pins cannot handle enough current to run most solenoids, relays or motors.

Common Anode Devices

Common anode devices present further problems because Arduinos are common ground devices. Even through the IO pins can sink current, you can’t switch them into a ground state the way you can switch them into a high voltage state.

Most of us are used to common ground — or common cathode — wiring style to control multiple lights or other electronic objects with a minimum number of wires. There, the positive feeds are isolated from each other so individual devices can be controlled, but they all connect to a common ground.

Common anode wiring is the reverse, where multiple devices share a power feed, but their ground sides are isolated from each other for control. Where resistors are needed to control current, as with LEDS, they are put on the cathode side instead of the anode side.

Extending the Pins

Running signals and other animation to any significant extent requires a strategy to multiply the outputs an Arduino can control in a way that is broadly compatible with available devices. Fortunately, there are readily available components that can significantly extend the I/O and current handling capabilities of an Arduino Board and allow control of common anode devices.

Shift Registers

HC595 Shift Registers (I use the 74HC595 variant) are logic ICs offering a basic way to multiply the digital output pins the Arduino can control. Using just three digital pins, an Arduino can control 8 output pins on the shift register.  Better still multiple shift registers can be serially connected, without any additional connections to the microcontroller, to extend the number of outputs under control to span many shift registers. I’ve previously written about shift registers in the Roundhouse rebuild.

To control a shift register, a byte of memory is needed to represent and manage the state of the register’s 8 pins. Accordingly, the maximum number of outputs you can control in a single chain of shift registers is primarily limited by the amount of memory available for managing them.

Consider, though, that a 100 bytes of memory allows you to control 800 digital outputs using just three Arduino pins. Let that sink in for a minute.

Shift registers are serial input, parallel output devices; the Arduino writes the bits serially, then all connected registers output on all data pins at the same time when the write is finished. Shift register outputs maintain their state–on or off–indefinitely until changed.

Darlington Drivers

Another basic tool is a ULN2803APG Darlington Driver, an IC that can switch higher voltages and higher current than an Arduino or shift register can handle. These are current sinking transistor devices, using NPN Darlington pairs; the addition of internal clamping diodes allow them to handle inductive loads such as relays, solenoids and motor driver applications like running unipolar stepper motors. LEDS and incandescent lights work well in common anode configuration controlled through a darlington driver.

Darlingtons allow a logic system (the microcontroller and attached Shift Registers) to control a set of outputs that are powered independently. So, for example, a 5 volt logic system can switch a 12 volt load (up to 50 volt max).  Very useful, yes? For current up to 500 mA per channel, Darlington Drivers can be a viable alternative to expensive relays.

The Good

An HC595 Shift Register plus a Darlington Driver extends the number of digital outputs a single Arduino board can control, using a common anode wiring solution that can handle virtually any kind of layout animation or control device. Using using Shift Register/Darlington Driver pairs and going to common anode wiring as my standard makes all connection and access methods uniform across a variety of devices.

The Bad and the Ugly

In theory, you just connect the output of the shift register to the corresponding inputs of the darlington driver, connect the darlington outputs to your devices, and you are good to go. Trouble is, the chip designers didn’t get the memo on that! The chips are a little difficult to interconnect: you can’t place the chips side by side and have respective outputs and inputs facing each other in the correct order. In fact, the HC595 connections are arranged a little oddly, requiring at least some connections between it and the darlington to cross over each other no matter what.

My first try was the roundhouse controller board. My problem then was trying to run some low voltage incandescent bulbs from 3.3 volt power. The darlington driver allowed me to do that with the 5 volt shift register.

Roundhouse Controller with an Uno

Roundhouse Controller with an Uno

See all those green jumper wires? That was my first solution to the interconnect problem on a single layer board; it works but it is awkward, bulky and hard to replicate. The additional interface for the addressable LEDS further complicates the board.

For signals on the test loop, I decided to try to shrink the board size, incorporate the necessary resistors (they are on a separate board in the roundhouse) and take a two sided approach using my favorite two sided prototyping boards.

Node Prototype 2

Node Prototype 2

As I was planning to record the block occupancy demo, I decided I needed more signals on the test loop to show the block occupancy system in action. I still had four available outputs on the board running the two Tomar signals– except those could not help me with a signal on the other side of the layout [the signals all have short lengths of thin magnet wire].

The HC595 can connect to another shift register serially, but I had not provisioned that on the boards built so far. It takes three connections to link to the next shift register: the two shared timing lines and the data output from the shift register.

Time to build board #3.

Node Prototype 3

Node Prototype 3

The board works fine. But creating these boards with prototyping materials is painful because of the number of jumpers to route and connections to make. As useful as these were going to be, it was going to take a long time to churn out a lot of them accurately. On the L&NC I expect to be controlling hundreds of lights and other devices around the layout. There had to be a better way.

Duino Nodes, Type A, Version 1

I was using fritzing, my favorite circuit design tool, to work on the circuit design for the next board and it became obvious that what I really needed to do was have a printed circuit board produced to my specs. Since I would need several boards for the test loop alone, and I was only just getting going, a small trial run of boards made sense.

I’m glad I did.  Here is the first version of what I call a Type A Duino Node.

Duino Node Type A

Duino Node Type A

These are double sided pc boards, pre-drilled and ready for components, with copper ground fill on both sides for emf control. It takes about 10 minutes to assemble a board for use. The prototypes took over an hour each to build, so the practical time savings for the dozens I’ll need on the L&NC is substantial.

They are 88 mm x 52mm; about 30% bigger than the smallest prototype I built. There are a couple of reasons for that: first, the board has Arduino-style mounting holes arranged to facilitate board stacking. Second, since these boards will run lights and other devices with varying current limits. generous space is available to mount an appropriate resistor for each cathode. A jumper can be used if a resistor is not needed, as might be the case when running a relay, motor or solenoid through a position.

On the right side are three control connectors: power, serial in and and serial out. When stacked, only short three wire jumpers are needed to chain from one board to the next. A terminal block is mounted on the opposite, output side of the board. There are nine positions: the common anode (power) plus eight switchable cathodes.

Deployment

There are four boards deployed on the test loop. One is dedicated to the two Tomar signals above.

Another board runs the dual signals below. The top searchlight is three aspect (red, yellow, green) and the bottom is two aspect (red, green), requiring a total of 5 outputs.

Dual Searchlight Signals, Scratch Made with BLMA Signal Heads.

Dual Searchlight Signals, Scratch Made with BLMA Signal Heads.

The last two Duino Nodes are used together for the station / signal complex.

The Station, and Signal #5

The Station, and Signal #5

The signal is three aspect (red, green, yellow). The station has a total of 8 individually switchable LEDS for internal lighting.  You may notice that the two sections of the depot have distinctly different lighting: the passenger station side has warmer, incandescent lighting (achieved with a mix of led colors); and the freight side has a cooler fluorescent lighting style (cool white LEDS).

One node is for the station signal that connects via four strands of magnet wire.

Duino Node controlling Station Signal

Duino Node controlling Station Signal

The second node mounts on top of the first, and it controls the Station internal lighting. The bottom node receives the incoming serial connection from elsewhere; then a cable connects the bottom serial out with the top serial in. There is no limit to the number of boards that can be chained and/or stacked together.

The Duino node for station lighting is stacked on top another node that runs the signal.

The Duino node for station lighting is stacked on top another node that runs the signal.

Here is a view of the test loop from below with all the Duino nodes in place.

Test loop from below.

Test loop from below.

It may be hard to tell, but the overall effect of using the Duino nodes is to simplify and compartmentalize wiring.

Using the Nodes

The real advantage of this system comes from adopting a uniform addressing system that makes it easy to randomly access and change any element on any node at any time.  I’ll go into that in the next post.


 

Block Occupancy Detection for DC and DCC, Part 2

In Block Occupancy Detection for DC and DCC I demonstrated the use of an ACS712 sensor and an Arduino Uno to sense current draw across the rails, the basis for most block occupancy detection systems. Assuming that one has also equipped some rolling stock with resistor wheel-sets, lighting or sound decoders, so that the entire length of a train is detectable, the theory is that current draw indicates that a block is occupied — and lack of current draw indicates that a block is clear.

In reality, it may not be that simple if you have devices drawing from track power other than locomotives and rolling stock. Any background current draw on rail power can interfere with the current sensing model.

Rail Powered Accessories

The Test Loop

The Test Loop

Keen eyes will notice that the test loop has a rail powered light on the Atlas track bumper at the end of the siding. I laid the track on the test loop long before I understood block occupancy detection.  I won’t do that again as I build the L&NC.

The problem is that the bumper light draws from the track itself and thus presents a constant load on that block. The draw of the lamp forces a slightly higher threshold for determining occupancy than would otherwise be appropriate.  Static loads on monitored blocks greatly complicate current sensing.

The best practice where current sensing is used to detect block occupancy is to feed accessories from a separate power bus. To use track power (as you might with a stationary decoder running a turnout motor), draw from outside monitored blocks—from a separate branch or sub-bus—to avoid confusing the occupancy detection system.

Solving the Continuity Problem.

While current sensing works well on a DC layout, as shown in the first video demonstration, the use of current as a control mechanism means that block occupancy is undetectable at times because of normal operation. Similarly, any transient loss of DCC track power (as with a short) will throw the occupancy detection system off for the same reasons. I think of this as a continuity problem.

The solution in both cases is to monitor the track bus with an extra sensor and lock the state of the system whenever the track bus is off. The simplest algorithm, puts it a slightly different way:

if track current is flowing then check blocks and update else maintain current state

E.g. ( in C++, where “master.on” represents the master current status):

if(master.on == true) {
  for ( i = 0, i < NUMBER_BLOCKS; i++) {
    // check block sensor i and update block status
etc......

For the cost of a sensor and a few lines of code the block occupancy system will now maintain its state correctly whenever there is a total loss of track power.

Wiring for Detection

Preparing the test loop for the Arduino & ACS712 sensor based occupancy detection system was a bit of a chore, primarily because current sensing requires some rethinking of the standard approach to layout wiring.

Wiring. Block sensors were added in Phase 2. Phase 3 signals and lighting in progress.

Test Loop Wiring. Block sensors were added in Phase 2. Phase 3 signals and lighting were in progress when this picture was taken.

The test loop represents my first crack at it. Needless to say, there is a list of things that will be done differently on the L&NC.

Routing Buses

The loop has a bus structure that, except for the lack of the DCC command bus (I connect my throttle directly to the booster when it is attached to the test loop), is the prototype for the L&NC.

Test Loop Connection Panel

Test Loop Connection Panel

The bus structure begins with the connection points on one end of the layout, mounted on a connection panel made from .080 styrene sheet. Every module on the L&NC will have one of these, with matching cables at the opposite side where it adjoins the next module.

Starting from the top the first two connection groups are polarized power connections made with color coded Anderson Powerpole connectors. A “Recommended Practice” per the Ntrak Manual, these things are a reliable solution for creating polarized power connections.  Some parts are available from Amazon; I find that Powerwerx.com has the best selection of PowerPole parts and supplies. The 15 amp gear should be sufficient for most N Scale layouts (an N Scale layout requiring more than that would be something to see!). Kudos to Ntrak for finding and adopting these connectors. BTW: the crimper is expensive but indispensable if one is going to make a bunch of Powerpole connectors.

The top group is the main DC power bus in three voltages: 12 (yellow), 5 (red) and 3.3 (blue) plus ground (black). This was also where I attached a label with the loop’s assigned IP address.

The next group down is the track bus (red & black); my DC power pack and my DCC booster can connect to the loop here with a matching plug.

The next two connections are an RJ45 port for Ethernet and a USB connection to the UNO. Both are  assemblies I got from Adafruit Industries. On the L&NC, the USB port(s) for attached Arduino boards will be located in an accessible place, away from the other connection groups (which will generally be hidden).

Connection Panel Bus Connections

Panel Bus Connections

Color coded power buses are routed along the edge to a central barrier strip where feeders take off to supply power where needed. On the L&NC I’ll choose different, unique colors for the track bus and feeders to reserve black for system ground and red for system Vcc (+5 volts DC).

Suitcase connectors are really popular these days for connecting wires without soldering. If you are not going to do occupancy detection then directly connecting feeders to bus wires with suitcase connectors is a clean solution. However, once you start down the road I’m traveling–whether your solution is off-the-shelf or homemade–suitcase connectors are not helpful. Instead, I find that PC board mounted screw terminals make easy wiring connections that are reliable and easily changed when necessary. When dealing with magnet wire, which you have to use in N scale if you want to run wires through scale light poles, conduits, etc., top-of-the-line PC board terminal systems are the ONLY reliable solution (the cheap versions will drive you crazy with intermittent connectivity).

ACS712 Board

ACS712 Board

The ACS712 sensor boards come with screw terminals for the monitored load, plus 3 pin headers that take standard 3 wire servo connectors for connecting to system power and the microcontroller. Wires that connect to the central barrier strip have crimped terminals.  I mostly solder at the PC board level and, less often, to make special cables (I solder track connections too, but that is a different issue).

Power Distribution on the Test Loop

Power Distribution on the Test Loop. The board in the upper right corner is for distributing 5 volt power to the signal system via PC board terminals.

On an L&NC module, the bus will continue from the central distributions point out to the edge configured to connect to the next module. One big change in module construction on the L&NC will make wiring easier: the cross frame members will be pre-drilled with large holes. That “little” gouge you see where wires cross the frame member at the bottom of the picture taught me that lesson.

On the test loop the 12 volt bus supplies the attached UNO with its Ethernet shield; the 5 volt bus supplies all sensors and actuators attached to the UNO and is generally considered system Vcc. The 3.3 volt bus is not currently being used on the test loop (but would be great for low current lighting or animations). All share a common ground (really important!). NB: I use modified Computer power supplies that  produce all three voltages at once with a common ground. Multiple DC power supplies can be combined to the same effect; just tie their grounds together to create the common ground.

Even on the test loop, the 5 volt bus is used so much that I need to create a distribution system to get power where needed. The lesson for the L&NC is  I will need to have distribution nodes for the whole power bundle in a few strategic locations on each module. Obviously, I need to do some more detailed wiring planning in advance so I know where everything has to go.

Routing Feeders

Current sensing encourages a nodal distribution system for track power. Instead of attaching feeders to the nearest track bus, the feeders are routed to an area where the sensors have been mounted. You could mount individual sensors at the points where feeders descend from the tracks above. In some situations that may work better; in other situations, aggregating the sensors in groups is the easier and more effective method.

Current Sensors and Block Feeder Connections.

Current Sensors and Block Feeder Connections.

ACS712 sensors read only one of the two rail conductors. On the test loop sensors are attached to the red rail.

I tried to complete the rail feeder connection with a board (with terminals) across from the sensors for the black rail connection points. I also ended up using the same board to centralize the power and data connections for the sensors and the servo for the turnout. In the future I will not mix track / control system connection points in this way.

Block Occupancy Detection in Action

Here is demonstration of the progress so far, with block occupancy detection active on all 4 blocks of the test loop. The signals are programmed to respond to block occupancy and the state of the turnout (the turnout actually has three unique states: “aligned main”, “aligned divergent”, and “in motion”), allowing you to see the system responding as trains move along the track. You’ll see it work in both DC and DCC — the layout works whether a power pack or a DCC booster is plugged into the track bus port. I have yet to see a single commercial occupancy detection solution that moves as easily between DC and DCC as this one does. I added a station with internal lights (connected to the same nodal system that supports the signals) to give just a little hint of the capabilities that will be unlocked on the L&NC.

In future installments, I’ll dig into the occupancy detect code again to give more insight into how it works. I’ll also go into the details of how I’ve implemented signalling on the test loop, including some special (and inexpensive) gear I’ve designed to allow a single microcontroller to run up to 255 nodes of signals and other kinds of lighting or animation.