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!

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.

Block Occupancy Detection for DC and DCC, Part 4

Through the first three parts of this series (links to part 1, part 2 and part 3) I’ve experimented with and refined to a degree the use of ACS712 current sensors for block occupancy detection. The system works well in DC mode, lighting up whenever a running DC train enters or is powered up in a block; program logic “remembers” block states when power is off for control reasons. My DC locos typically start drawing 30 – 50  mA when the lamps come on.

In DCC mode, ultra low current detection becomes an issue and the off-the-shelf ACS712 sensors don’t meet every need. My BLI DCC/Sound Locomotive draws enough power to be detected with the current system in idle mode, all sound and lights off. However, some standard DCC decoders draw so little current in idle mode that they are not consistently detectable. Further, constant track power in DCC invites us to find a way to sense any object drawing some minimal increment of current — such as 1.1 mA for a 10KΩ resistor wheelset on an 11 volt (in N scale) feed. There are a number of obstacles to achieving 1 mA  sensitivity with ACS712 sensors.

The Challenges

First, there is a question of how low a current the ACS712 can resolve. Theoretically, because the chip responds in a ratiometric way to current input, any amount of current will provoke a proportional output response. In reality, the output of the chip is a little noisy, and the noise masks the low current response.

Allegro MicroSystems says that the best resolution with the optimum filter capacitor is 20 mA. There is some general agreement among internet cognoscenti that with some amplification of the signal from the ACS712, greater sensitivity should be possible.

Second, the 10 bit ADC built into most Arduino boards has a maximum resolution of 4.88 mV (5 volts / 1024 steps), limiting the minimum detectable current to 26 mA (4.88 mV resolution / 185 mV/A sensitivity). Even the 12 bit ADC found in the Due and Zero boards is not quite close enough, with a maximum resolution of 1.22 mV (5 volts / 4096 steps), resulting in minimum detectable current of 6.6 mA.

A Better Analog-to-Digital Converter

Of the two problems, this is by far the easier problem to solve by using an external ADC with a 14 or 16 bit resolution. A 14 bit ADC has a maximum resolution of .305 mV, which is a good resolution for consistently detecting current at the 1.6 mA level or higher; a 16 bit ADC would provide 76 µV resolution and current detection in the mid to high µA range.  For those wanting to detect a single resistor wheelset, 16-bit is the way to go.

For my purposes and goals, I’m going to see how it goes with 14 bits so I’m not pushing resolution past the point of usefulness at this stage. My thinking is that 1.6 mA should be sufficient to detect a pair of resistor wheels. Two 10kΩ resistors in parallel have a resulting resistance of 5kΩ, which at 11 volts will draw 2.2 mA (@16 volts, 3.2 mA). Assuming I can overcome the noise problem to the point where 14 bits of resolution provides accurate current detection, the final step would be to go to 16 bits.

I looked at several ADC products and settled on the Mayhew Labs Extended ADC Shield, which is also available at Amazon. I chose this for several reasons: it supports 8 inputs, comes in a shield format and (perhaps most importantly) offers enough bandwidth to be able to sample multiple sensors at a reasonable rate.

Mayhew provides a code library for reading a variety of sensor types through the shield. It is fairly straight forward to use, and the shield is a very good quality piece of gear. I have found other ADC boards, but none with the unique capabilities of this one.

Mayhew Labs Extended ADC Shield

Sparkfun Low Current Sensor

Sparkfun sells a breakout board as a low current sensor using the ACS712 sensor chip plus an operational amplifier to amplify the signal. This is the only commercial solution of its type I’m aware of, so I bought one to check out and test. The schematic for the board can be seen here.

SparkFun Low Current Sensor Breakout – ACS712. This image is from an older version; different trimpots are used in the current version.

Although the circuit is promising, this board is really an experimental item and not suitable for production use on a model railroad. Part of the problem is that it does not provide — and is not drilled for — standard screw terminals for attaching the input current source, adding additional challenges to deployment. On the input side (I+ / I-) it is drilled for a pair of header pins and two larger holes with contact pads. The control side (VCC, OUT, GND) is drilled for standard headers.

Secondly, because this is an experimental board, it has two trim-pots for configuring the Op-amp.  Sounds great, but in practice this setup doesn’t work well. Add sketchy instructions for setting and using the board and I think most will find this board impractical for large scale use, though an interesting experimental tool.

Learning By Failing

So when the board arrived, I soldered on some header pins and hooked up the sensor to an UNO with the Mayhew ADC Shield, then attempted to configure and use the board. Here are the setup instructions in their entirety:

“To calibrate, first set the output offset to the desired level (with zero current on the sense lines, read output with a DVM). Then with a known current input (a 100mA limited supply works well for this), set the output deflection with the gain pot. Sensitivity is then calculated as (Vref – Vdeflect)/(current input).”

The “output offset” is (presumably, though not literally stated) adjusted with the vref trim-pot.  But what “level” is “desirable” for this application?  The second instruction is even weirder, since you are not going to short out a power supply by directly attaching it to the sensor without a load, and its the load that determines the current flow. I’m sure they meant to say something like “supply a load with a known current draw.”

I tinkered fruitlessly with the trim-pots for hours, testing various theories about how it should work and getting nothing intelligible out of the sensor. The gain pot is straightforward enough, resulting obvious changes to readings as the trim-pot is adjusted. Its the vref adjustment that mystified me and seemed to have no logic. I  did notice that when setting it there was a point where the output would suddenly, but only briefly, drop to O. That zero point is so finely specific that it is essentially impossible to set the trim-pot at that level; it always ends up off one way or another. That was a clue, but I did not yet understand.

Back to School

I found a nice tutorial about Op-amp circuits and, after a while started to understand the circuit and comprehend the problem. If you don’t understand Op-amps (who does among those of us not trained in electrical engineering?), check out the tutorial before reading further here.

The Op-amp circuit Sparkfun uses is a “voltage subtractor,” the intent of which is to  subtract the input voltage from the reference voltage and amplify the difference. This is the right choice—I think—but the implementation is wrong, at least for my purposes.

Unique ACS712 Properties

Many sensors that one might use with an Arduino are straight forward linear output devices where the output voltage ranges from 0 to 5volts in proportion to an input (light, temperature, etc.).

What makes the ACS712 different is that it senses both polarity and current of the measured input.  The “quiescent voltage” we measure when calibrating a sensor is the sensor’s “zero” point: ideally VCC/2 — midway between 0 and VCC (nominally 5 volts).  When the polarity is one way the measured current is represented by a value above VCC/2; when the polarity is the opposite, the sensor produces a value under VCC/2.

That means that we are only interested in the offset between the sensor output and its quiescent value. The software calibration routine I’ve been using seeks to get the most accurate average mid-point value possible to enhance the accuracy of the offset measurement. Amplifying that offset should be the route to gaining sensitivity.

Shouldn’t vRef be VCC / 2?

It may well be that the vref adjustment has value when measuring DC current with a fixed polarity. However, I’ve seen no math or theory in support of that proposition. For measuring DCC current, which is an 8kHz alternating polarity wave form, there is only one correct reference voltage for comparison to the ACS712 output: VCC/2.  So, Sparkfun had the right idea using a trim-pot as a voltage divider circuit to generate the reference voltage, but the trim-pot inhibits setting vref to VCC/2 because it is too imprecise to set the two resistor legs to exactly the same value.

What Now?

The Sparkfun sensor experiment was a bust in that it did not produce a usable result.  But it did help me research and think about what it is I need an operational amplifier to do in order to successfully amplify the ACS712 signal. Sometimes we learn more from failure than we do from success.

The next step is the set up an Op-amp with a fixed reference voltage of VCC/2, then continue experimenting from there.  I have the parts. In a few weeks, if time permits (between work and our ailing Beagle, time is tight right now), I should have some sort of result.

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.


 

Chasing Electronic Gremlins

I built the test loop for a couple of reasons. First I needed to revive my long unused track laying skills. Second, I needed a place to test and repair locos and rolling stock. Third, and perhaps most importantly, I needed to learn how to deploy Arduinos on a layout in a bullet-proof sort of way, before investing time and money building the main layout.

If you’ve been following along, you know that lighting is one of my big challenges in building the layout in the chosen location. The soffits above the bar are a thin skin of paneling, with little structure supporting it, hiding HVAC duct-work. Standard light fixtures are not possible here.

Addressable RGB LED Strip

Addressable RGB LED Strip

That constraint started a search for a lighting solution that was light enough to affix to the paneling with 3M Command Strips, but would produce enough light to effectively light the layout. When I found strip ALEDS, I knew I’d found a solution. The first two light bars I made are demonstrated here (a simple light show accompanied by a little Debussy):

The bars are easy to create.  Mine are sized at 26″ long; the right size to both light from above and install on the underside of the top level of the layout to light the lower level.

To make them I split 1/2″ PVC pipe on a table saw, then cut the pipe halves to length [TIP: PVC pipe from your home store is dirty stuff. I clean the cut halves with denatured alcohol before final assembly]. I attach 1/2″ reflective Mylar tape to each inside half of the pipe (creating a reflector), leaving a strip of bare PVC down the center of the pipe.  A bead of Liquid Nails for Projects down the middle holds a prepared (with JST 3 wire connectors at each end) 38 LED strip.

My standard RGB LED light bar.

My standard RGB LED light bar.

The demo above shows two bars chained together. You can keep lengthening the array by adding additional bars, at least until you reach the limits of your power supply.

Not So Fast

I have to admit that when I made and tested 4 bars together (152 LEDS), I was  disappointed with the amount of light I was getting. It was good, but just not quite enough.  Two more bars (228 LEDS) ought to do it I thought.

What I got when I expanded the array to 6 bars was a very obvious light intensity drop off (and resulting color change, since these are RGB LEDS) from the beginning to end of the array. Nowhere in the information I’ve assembled about ALEDS has there been any mention of this problem.  I got out the multi-meter and, sure enough, the supply voltage drops steadily as you progress along the strip; and the greater the total number of ALEDS chained together, the more pronounced the effect throughout the strip.

Well, I’m a model railroader and I know all about resistance and current drop off; this is our classic problem of current loss over long runs. The solution? A 16Ga supply bus that injects current every two bars.

Light Controller and Bus Bar

Light Controller and Bus Bar

Head end of the lighting bus bar.

Head end of the lighting bus bar.

A strip of plywood provides the mounting surface for the required capacitor near the first LED, the bus wire (I CA’ d it to the wood) and circuit board fragments with with PCB screw terminals.

The test loop under lights.

The test loop under lights.

Problem solved.

Booting a Loaded Arduino

The basic reliability of the Atmel platform used by Arduino boards is impressive. So when I started seeing boot problems, I was puzzled.  In all cases, the problem occurred on initial power up; rebooting the affected board by hitting the reset button solved the problem.

This was not a good development.

My first three loaded up Arduinos are installed on the Test loop, Lighting Control and the Control Panel.  All three have an Ethernet Shield and are attached to additional devices. All three evidenced cold boot problems in one form or another.

It had to be a power problem.  The additional load from the Ethernet Shield and other devices (although, in most cases I supply power to attached devices separately so they don’t draw from the Arduino’s limited current handling capacity) had to be the issue. One of the confusing things about UNOs is that you can power them from USB at 5 volts DC, or from a separate DC power supply at 7 – 12 volts.

Umm, how much power should I be supplying?

Enercell Power Supply

Enercell Power Supply

In the context of the control panel, where an UNO has an Ethernet shield with multiple digital and analog connections to the touchscreen, I found that I need to supply 12 volts.  At that level the rig is 100% reliable, something I easily established with the help of an adjustable power supply. The trade-off with the control panel, because everything is enclosed, is heat buildup, requiring a fan I didn’t originally plan for.

New deployment rule: the standard power supply for Arduino boards with built-in voltage regulators (primarily UNOs and MEGAs on this project) will be 12 volts DC. Connected devices will run at the standard logic 5 volt level. Smaller Arduino boards without a voltage regulator will get 5 or 3.3 volts DC as required.

Modified Computer Power Supply

Modified Computer Power Supply

I use converted computer power supplies with simultaneous outputs at 3.3, 5 and 12 volts DC, so my layout bus has all three feeds.

It may not seem like it, but that is progress.

Powering Up In Order

Unlike the control panel, the lighting controller did not settle down with a 12 volt supply. There, the Ethernet Shield would go into an initialization loop (attempting to start up and failing, over and over) on power up — but would work fine after a hard reset.

On the test loop, the problem was even subtler: upon cold power up everything appeared normal and the sketch would start to execute…. then freeze at the point where it is supposed to send a broadcast message across the network.

It had to be something about power again that manifests only on a cold start, but what? Faulty Ethernet shields?

Here the clue was a little warning from Adafruit about neopixels (ALED strips): always make sure the power supply to the strip is on before the data connection from the Arduino goes live, or the strip could be damaged.

I always figured that if the Arduino and the ALEDS (and other peripheral sensors and actuators) were powered from the same source and came on simultaneously, Adafruit’s warning would be satisfied.  Since I’ve never had damage to the strip, and I’ve been working with the same strip for some months now, I think technically I was right.  However, it seems that from the Arduino side, simultaneous start up is not necessarily so blessed, especially when attached to an Ethernet shield.

I conducted a simple experiment on the lighting controller:  I unplugged the power from the board/shield combo then powered up the ALEDS before plugging the power into the board.

BAM. Worked perfectly every single time. No confused Ethernet shield; perfect response to commands; no hitting the reset button.

Of course, manually plugging a fleet of embedded Arduino boards was not going to do at all.

Automating Power On Delay

Consulting the Internet Machine, I found a simple power-on delay circuit.  In my first attempt I built it as shown, except for substituting a variable resistor for R2 (on original schematic) to allow some adjustment of the delay.  For the relay, I chose a low power signal type — adequate for the power draw of the Arduino/Shield, but possibly not sufficiently durable for this application. Only long term experience will tell.

Anyway, as built it provides about a 50 – 100 millisecond delay in powering on the board. That turns out to be enough.  With the delay circuit attached, the lighting controller powers up perfectly every time.

I modified the circuit slightly for my second build, including both input and output indication LED’s [ green for input power on, and blue for output power on. ] and increased the size of the capacitor to 100µf. The bigger capacitor gives a little more time range to the delay (as adjusted by R4; if you go out of range either direction on R4, the circuit will not work.) from about 1/10th to 1/2 second. The I/O LEDs really help see the timing of the delay.

Here’s schematic of the board as I’m building it now:

Power-On Delay Circuit Schematic

Power-On Delay Circuit Schematic

Built on one quadrant from an SB4 Snappable Breadboard (these are my go-to, two sided solderable breadboards), the top looks like this:

 

Power-on Delay Circuit Top

Power-on Delay Circuit Top

And, the bottom:

Power-on Delay Circuit Bottom

Power-on Delay Circuit Bottom

Installed on the test loop and in operation:

Uno, Ethernet Shield and Power-on- Delay board.

Uno, Ethernet Shield and Power-on- Delay board, mounted under the Test Loop.

From here on, power on delays circuits are another standard component for reliable operation, though I think I’m going to double the size of the resistor on the blue led to tamp down its brightness more!.