Arduino Microcontrollers

Microcontrollers (MCU) – the main electronic device on Arduino boards is precisely MCU, making the control system radically simplified. Instead of connecting multiple electronic components into a common circuit, you can use a universal device.

Moreover, unlike specialized devices, you can independently change the appointment of Arduino, turning it into a timer, and at the same time a controller for many servos and much more.. And you don’t even have to think about matching currents and voltages, digital devices does not operate with voltage, but with two states – HIGH and LOW. They are 0 and 1, or FALSE and TRUE.

Formally a microcontroller is a small computer on a single integrated circuit. In fact, microcontrollers are a very cheap and convenient electronic component and they surround you from all sides. They are inside the TV remote control, your cars, household appliances and even DCC railroad control systems and decoders work exclusively on them. However, up to now microcontrollers have been associated with terrible words – programming and firmware. I hasten to reassure you, Arduino is no more difficult than connecting the wires between DC motor and the battery.

Many modelers are conservative, and very wary of novelties. So, Arduino is not a new invention, it is a well-established platform with a 15-year history. The most important thing is to understand how it works and why it is needed.

Arduino is an open-source electronics platform based on easy-to-use hardware and software. Arduino boards are able to read inputs – light on a sensor, a finger on a button, or a Twitter message – and turn it into an output – activating a motor, turning on an LED, publishing something online. You can tell your board what to do by sending a set of instructions to the microcontroller on the board.


Arduino NANO

Arduino NANO

Advanced users can use my project with any microcontrollers (ESP, Intel, PIC, STM and other), but I recommend the classic Arduino – MEGA, UNO, and NANO based on Atmega MCU. The Arduino platform is constantly evolving, and now the site presents modern hardware. For the URB project, these opportunities are redundant, so I use equipment from the chapter ENTRY LEVEL.

And here are the reasons for this:

  • they are cheap, very very cheap and very reliable.
  • the supply voltage (and, accordingly, a high level of a digital signal) is 5V, which means that compared to the 3.3-volt logic of other microcontrollers, you will not have problems transmitting signals over long distances. And the output current for each pin of the classic Arduino is greater.
  • the microcontroller frequency (16 MHz) is sufficient to control any systems for railway modeling, it makes no sense to use real-time high-speed microcontrollers with frequencies from 100 MHz and above.
  • Unlike more powerful models of microcontrollers which have an operating system, multitasking and more, Arduino on Atmel chips have only an infinite loop and they are very simple to program.

So, I prefer NANO because it is the smallest in size. And please purchase a minimum of three Arduino NANO boards for create an Arduino network.

 

Arduino MEGA

Arduino MEGA 2560
Screw Terminal Block Shield Board Kit For MEGA 2560

The Arduino Mega 2560 is a microcontroller board based on the ATmega2560. It has 54 digital input/output pins (of which 15 can be used as PWM outputs), 16 analog inputs, 4 UARTs (hardware serial ports). However this causes some difficulties – connecting so many wires to this board always causes errors. In addition, the sketch becomes very complicated and long. The most common problem is the reliability of contact connections. The last problem can be solved by using Prototype Screw/Terminal Block Shield Board Kit for Arduino MEGA 2560 with screw connectors. I recommend using MEGA only as COMM, and only if your layout is large enough and involves connecting many external modules.

If you are just starting to master Arduino, then please use less complex Arduino boards (NANO or UNO).


void loop()

Blink sketch

Returning to the concept of Arduino. After the introduction, it is already easier to explain: the Arduino board is a thing that will obediently carry out your commands that you entered using the Arduino IDE. That is, the sketch that you wrote in the Arduino IDE, and then uploaded into the Arduino board is just a list of commands and actions.

Blink is the most famous sketch in Arduino environment – it simply flashes the LED once every second. But more importantly, it very simply explains what Arduino programming is and what a loop is.

void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   
  // turn the LED on (HIGH is the voltage level)
  delay(1000);                       
  // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    
  // turn the LED off by making the voltage LOW
  delay(1000);                       
  // wait for a second
}

How run and stop Arduino board

This is a very unexpected question, and short answer: it can't be done :)

The fact is that the Arduino microcontroller runs constantly, without stopping it scrolls through the software loop described above. As soon as you turn on the power to the Arduino board or upload a new sketch, the program will start, when you turn off the power, the microcontroller will stop. The only thing you can do in the process of working is to press the RESET button, which will force the microcontroller to start performing your sketch from the beginning.

Which I deliberately wrote this inexact notion «program». The word sketch used in the Arduino environment has one more meaning: since the loop principle is used, unlike computers and microcontrollers with an embedded operating system, you can run ONLY ONE «program» and this is the sketch.

This is the advantage and disadvantage of the Entry Level Arduino. On the one hand, it is very simple, you will not go wrong in the code, since it is executed sequentially line by line and only the order of commands matters. On the other hand, in this system it is impossible to organize multitasking, that is, to simultaneously perform several actions.

Arduino Reset button

For the URB project, this Arduino feature is a very convenient. You do not need to wait for programs run or establishing network connections, you just turn on the power switch and everything works right away. Since the project initially involves the use of multiple Arduino boards, multitasking is created by using multiple microcontrollers.

The URB project also uses software reset.

Motor Drivers

We can control the speed of the DC motor by simply controlling the input voltage to the motor and the most common method of doing that is by using PWM signal. On the other hand, for controlling the rotation direction, we just need to inverse the direction of the current flow through the motor, and the most common method of doing that is by using an H-Bridge.

Motor Drivers

You can use any motor-drivers in the URB project without restrictions, you need only adapt the sketches to your motor-driver. The motor-driver is selected according to the electrical characteristics suitable for your railway. First of all, the voltage and current at the output of the motor-driver matter.

The differences among motor-drivers for the Arduino are mainly in the number of control pins. Basically, there are motor-drivers with three and two control signals (pins) per channel.

L298N

The dual-channel L298 uses the first method, and it has 6 control pins. The principle is as follows – the PWM pin (ENA) is output separately, changing the logic levels at IN1-IN2 terminals changes the state of the H-bridge and, accordingly, the polarity and direction of rotation of the DC motor. Same thing for channel B. If you put jumpers on PWM pins (ENA and ENB), you get a current and voltage booster with a polarity switch. In this mode, L298 can be used to control two-wire electromagnetic point-motors, such as KATO.

All sketches on the site use this motor-driver.

Control L9110 via two wires

The control of motor-drivers with two wires per channel is somewhat more complicated, since the PWM signal simultaneously sets the direction of rotation. That is, if a low logic level (LOW) is on one pin, then a PWM signal must be output to the second. If you change the situation, then the rotation of the motor will become opposite. Accordingly, you need to change the sketch code to:

void controlPlayer() {
  …
   // Direction and Stop
  if (inputString.charAt(1) =='d') {
    if (inputString.charAt(2) =='f') dirForward = true;
    if (inputString.charAt(2) =='b') dirForward = false;
    if (inputString.charAt(2) =='s') speedTrain = 0;
  }
  if (dirForward) {
    digitalWrite(PIN_A1B, LOW);
    analogWrite(PIN_A1A, speedTrain); // PWM
  }
  else {
    digitalWrite(PIN_A1A, LOW);
    analogWrite(PIN_A1B, speedTrain); // PWM
  }
  …  
                     

Relays and Busters

The voltage on the Arduino pins is equal to the supply voltage of the MCU. ATmega328 can operate in the range from 1.5 to 5.5 V. Therefore, if you connect Arduino to power of 3.3V, then the high level voltage on the GPIOs (pins) will also be 3.3 V. The current for each GPIO in OUTPUT mode is no more up to 40mA. Such voltage and current are sufficient only for signal LEDs, while it is necessary to install a series-limiting resistor of near 100 Ohm.

A more powerful load can be controlled by Arduino using boosters or relays. One of the options for boosters (current and voltage amplifiers) is the motor-driver discussed above. In most cases, a change in polarity is not necessary, so it is enough to assemble a circuit from several transistors. In the URB project, instead of transistors, ULN2X03 chips are used, where these transistors are already assembled into a Darlington Array. You can also use any other current output drivers on chip.

Darlington Array ULN chip

Busters on ULN2X03

I use two variants of Darlington Array chips – ULN2003 and ULN2803. This is the most common chips used in Arduino circuits. Several motor shields are built on these chips, as well as a stepper motor control module. The connection of these chips to Arduino is simple, a distinctive feature of the circuit with these chips have a common positive wire, in contrast to the usual method with a common GND.

Connection of ULN2003
Arduino relay module

Relays

If you need blocked a track section of rails, then you need a switch for control it. An electromechanical relay controlled by Arduino solves this problem. Ready-made modules with different number of relays are cheap, but you should pay attention to the principle of their operation. These modules have four states that must be considered when programming sketches.

Relay states

Sensors

We can apply ANY sensor to Arduino, including such an exotic one as a pressure sensor. However, most of the sensors are large enough, for example, an ultrasonic sensor is very difficult to incorporate into the layout imperceptibly. Also, there are some difficulties with the probability of triggering sensors based on reflection of visible and infrared spectra. In any case, you can experiment and get your own successful designs.

I mainly use Hall sensors, they provide guaranteed triggering and are very easy to install and configure. Also, I apply the infrared sensor together with the IR-LED in one housing. However, when using IR sensors, there are several problems: different pickup distance due to the color of the rolling stock (the more lighter the color, the longer distance of triggered) and a false signal of triggered at change of moving cars of a train in a zone of action of the gauge (gap zone triggered). It is also difficult to avoid the sensor's response to multiple reflections of infrared rays from the details of the layout and train and the influence of sunlight.

But in a situation where you need to get a constant signal while passing the entire train through the sensor zone, the infrared sensor is preferable, only you need to modify its design as on video.

Hall Sensor

In comparison with other sensors, it has the advantage of a trigger «dot». The second element – the magnet – is attached to any metal part underside of a car or a locomotive (for example, to the fastening screw, etc.). This allows you to correctly and accurately set the pickup location relative to the train and relative to the location on the layout, as well as easily adjust it by moving the magnets. You can place a magnet on any car or locomotive, at the beginning, middle or end of the train, thus adjusting the stopping place to within a centimeter.

Install Hall sensors

I recommend small cylinder neodymium rare earth magnets. By changing their number, you can adjust the distance between the magnet on the car and the sensor on the rails. I have reliable operation at distances of 1-5 mm. Hall sensors are small, if they are neatly put between the rails, then they are like real AWS inductor.

IR-module

On this module I separated the infrared sensor emitter and receiver. These details deployed relative to the rails by 45 degrees and are located at a certain height above the rails. Also on the receiver is a black slit mask that removes stray radiation.

The height of the sensor and the IR-LED above the rails for different scales is selected experimentally based on the minimum horizontal continuous line of wagons in your collection.

This design allows you to get a guaranteed signal of the presence of a train at the sensor zone. The system works correctly at any speed of the train, any the number of cars or types of cars and any length of the train.

Install Hall sensors

This design can be masked in relay cabinets located on the both sides of the rail tracks. See chapter Ideas.

Conclusion

In my opinion, it is wise to combine both types of sensors depending on the purpose. For example, IR sensors are more convenient for a railway crossing barriers, and Hall sensors for stopping at a dead end or at a station with automatic control (AWS and automatic script commands of the URB).

For example, the video interlocking system works with two types of sensors.

And one last point. For Arduino, the logical states of operation of any sensor do not matter, you can always invert them in the sketch code. For example, if you made my design with an IR sensor, you will notice that the sensor is triggered when there is no train (the logical state is HIGH), and when the train passes, the state of the sensor is off (LOW). A simple if (digitalRead(SENSOR)==LOW) {...} code will change the signal from the sensor to the opposite.

Sensors as feedback can also be used to accurately position the turntable and so one.

Servo HG-90

Servos

A Servo is a small device that incorporates a two wire DC motor, a gear train, a potentiometer, an integrated circuit, and an output shaft. Of the three wires that stick out from the motor casing, one is for power, one is for ground, and one is a control input line. The shaft of the servo can be positioned to specific angular positions by sending a coded signal. As long as the coded signal exists on the input line, the servo will maintain the angular position of the shaft. If the coded signal changes, then the angular position of the shaft changes.

Built-in Servo library

Servo control is a built-in Arduino IDE function. Arduino generates a value in microseconds (ms) to the servo, controlling the shaft accordingly. On a standard servo, this will set the angle of the shaft. On standard servos a parameter value of 1000 is fully counter-clockwise, 2000 is fully clockwise, and 1500 is in the middle. You can connect the control (orange) wire to any GPIOs of an Arduino. That is, you can connect up to 12 servos to Arduino NANO (UNO), and 48 servo to Arduino MEGA. The integrated library Servo.h will generate a control signal to all Arduino pins individually.

There is one feature of this library – it uses the Timer 1 of ATmega328 MCU to generate a control signal. I use this Timer for PWM control of trains, and in the URB project, the frequency of Timer 1 is reduced to reduce the PWM duty cycle to 122 Hz. If you still need to connect both motor-drivers and servos to one Arduino, then use the alternative ServoTimer2.h library. Therefore, do not use this library on those Arduino to which motor-drivers are connected if you don’t want to lose control of trains.

VarSpeedServo library

Servo.h library has a limitation on control of a servo – you cannot control the speed of the servo shaft. The servo lever will turn to the position you set with the maximum speed that the servo mechanism is capable of. But in modeling, it is often necessary to adjust the rotation speed for more realism. This task solved with an alternative library for servo control.

The VarSpeedServo.h Arduino library allows the use of up to 8 servos moving asynchronously (because it uses interrupts). In addition, you can set the speed of a move, optionally wait (block) until the servo move is complete, and create sequences of moves that run asynchronously. A good example of the application of this library is the rotation of a turntable using a servo.

Servo Turntable animation

DC and Stepper motors

PWM and a train control

The default PWM sampling frequency for ATmega328 and ATmega2560 is from 500 to 1000 Hz, depending on the selected GPIOs and Timers of MCU. These frequencies are in the sound range, and you can hear the unpleasant squeak of the engine of the locomotive, especially at the start moving. Preconceived opinions of some modelers is the need to set the PWM sampling frequency above 16 kHz so that this squeak is not audible. This is the wrong opinion – the higher the PWM frequency, the worse the traction characteristics of the DC motors.

My experience gained as a result of my own experiments is confirmed by manufacturers of model locomotives with DCC control – do not increase, but rather lower the frequency. The frequency of the PWM on DCC decoders is about 100 Hz. Therefore, in the Setup void code block, you can see a code like:

// Set PWM frequency for D9 & D10
// Timer 1 divisor to 256 for PWM frequency of 122.55 Hz
  TCCR1B = TCCR1B & B11111000 | B00000100; 

This code depends on the type of MCU (see snippets). That is, the URB project fixed motor-drivers to a sampling frequency of PWM equal to 122 Hz. For the world of Arduino the PWM method of management is native, you do not need to study the principles and subtleties of PWM working. There is a simple code that implements this method in one line: analogWrite(pin, value |0-255|).

Individual traction settings

For small collector DC motors (respectively, with a small weight of the motor armature) the minimum threshold of change in revolutions under load is about 0.3 V on the linear part of the graph, and about 1 V at low revs. Moreover, the higher the voltage for which the motor is designed, the greater this value. That is, it makes no sense to use 100 or even 50 speeds, it will not affect the feeling of driving the train.

The linearity parameter has a much greater meaning; it is a completely different way to enjoy your locomotive control. And this is exactly what is implemented in the project. You can individually configure each of your locomotives for the application; for this, the project provides a speed table with 255 speed levels. By changing this table, you can rearrange the curvilinear characteristic of your engine to linear (I will tell you a secret that such a table is used in DCC decoders).

Once again, the problem is not that there should be a lot of speeds, but their distribution over the control range.

The latest versions of my application use 24 speeds. This is more than enough for the smooth movement of any type of locomotive. Nevertheless, the project has the ability to customize traction modes.

Custom speed table

In the headings of a sketch I entered an array named speedArray#. The numbers listed in it correspond to the output level of PWM. By changing these numbers you can change the characteristics of the locomotive, making it, for example, very quick, or on the contrary to achieve a smooth acceleration or braking at low speeds. By default, it is configured almost linearly:

//Speed               1   2   3   4   5   6   7   8   9   10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  
byte speedArray [] = {20, 30, 40, 50, 60, 70, 80, 90, 100,110,120,130,140,150,160,170,180,190,200,210,220,230,240,255}; 

Stepper motor 28BYJ

A stepper motor, also known as step motor or stepping motor, is a brushless DC electric motor that divides a full rotation into a number of equal steps. The motor's position can then be commanded to move and hold at one of these steps without any position sensor for feedback (an open-loop controller), as long as the motor is carefully sized to the application in respect to torque and speed.

28BYJ-48 is unipolar stepper motor with gearbox has five wires and four coils (actually two coils divided by center connections on each coil). The center connections of the coils are tied together and used as the power connection. They are called unipolar steppers because power always comes in on this one pole.


Power

The power for an URB control system are divided into two branches, one for moving trains, the second for electronics and devices on the layout. Thus, with short circuits on rails and other troubles with trains, the layout control will not be affected. For simple track-plans use any charger for modern smartphones with a USB connector. The current of such chargers should be about 1 A. For the movement of trains, you can use the transformer you already have from the starter set or any DC power supply with 12V. Please note that the output current also should be about 1 A or more. For larger layouts, use appropriate power supplies. Pay attention to the address wire gauges to a power wires from the current calculated by you.

It is convenient to carry out the connection of wires between the power supply unit and the motor-driver through the power plug-screw terminals. If you want to increase or decrease the voltage for locomotives of your favorite scale (for example, up to 18V), then connect the power supply with the voltage you need to the motor-driver.

The ideal solution can be a computer power supply, it immediately gives out voltages both 5V and 12V with protection. Also, you can apply two standard power supplies, to 5V and 12V, by combining their negative wires together.

The video shows how to connect power supplies and calculation methods of current for your layout.

Power Supply

URB unit

Assembling of the circuit by connection wires over the breadboard is a very inconvenient task. As the circuit becomes more complicated and components are added, problems are introduced with the correctness and reliability of connecting the wires and blocks. Therefore, I suggest you make a URB unit (Free GERBER-file) that solves not only these problems but also adds tremendous new functions. You can create a similar scheme on the breadboard, but URB is much more convenient!

This board uses Arduino NANO. Therefore, the dimensions of URBs are only 60x70 mm, which makes it possible to hide it even inside model building. This solution provides excellent flexibility, maintainability, simple mass production and low cost. The board is designed to avoid incorrect connection of Bluetooth modules and Arduino NANO.

To the functions of Arduino, the board (URB unit) adds the following capability:

  1. Connectors for two Bluetooth HC-05 (HC-06) modules
  2. Direct plug 3 servos or 3 sensors
  3. Direct plug relay block
  4. Direct plug motor-driver aka L298 or similar
  5. Screw plug stepper motor
  6. Convenient screw connections
  7. 6 (7) High-Current outputs (Up to 0.4A per channel)
  8. High-Voltage Outputs up to 50 V
  9. Built-in I2C bus
  10. Optional: install I2C pull-up resistors and smoothing capacitor for power supply

The I2C bus needs resistors pulling the data line to a high potential. You can install resistors of any type on the board. I recommend 10K resistors. I also recommend the use of a smoothing capasitor 1000mf x 25V, when a URB connected to many LEDs, relays or servos, to avoid voltage drop when they turn on.

Details

URB 2 details
  • PBS-15 (HO27): 2.54mm pitch PCB female single row 15 pin — 4 pieces (or 15 pin – 2, 6 pin – 2, 4 pin – 2).
  • PLS-40: 2.54mm 40 pin male single row pin header connector — 1 piece.
  • DIP IC Sockets 16P — 1 piece.
  • 2 Pin screw PCB terminal block connector 5mm pitch &nmash; 12 pieces.
  • ULN2003A (DIP16 package): High-Voltage, High-Current Darlington transistor arrays — 1 piece.

URB unit circuit

Modellers asked me to show the circuit diagram of the URB unit. In my opinion, this is superfluous information, as these are just connectors and their connections, and Arduino pin numbers are written in header of any sketch to help you understand the diagram. And yet, here this circuit.

URB 2 circuit Download GERBER URB 2 FINAL

How get URB unit

You can download the GERBER-file for free and send it to any PCB manufacturer. I order PCB from the Seeed.com. You will need to solder the elements to this board yourself.

Alternative to URB unit

If you do not want to solder the URB unit yourself, you can buy a ready-made adapter for Arduino NANO in any online radio parts store. Using it is slightly more difficult than the URB unit, but thanks to the screw contacts, you will get a much more reliable circuit compared to a breadboard.

Typical connections

GPIOs of the microcontrollers are mostly universal. That is, you can connect your devices to any Arduino pin. URB unit is designed to connect them quickly. There are many options, the pictures in this section show the most common connections.


Sensors


Bluetooth modules


Motor-drivers


Relays


Servos

Buyers guide — How to cheap buy details of Arduino

I did not want to write this guide for a long time, because I thought in Internet the information was enough to indicate that this is a very cheap project. I am the same buyer of these goods as you are. That is, I do not produce, sell or advertise the producers of these details. And I do not have any benefit from such activities.
But I was wrong, it turned out that this is very important. I will give my method of buying these goods and the approximate prices.

The first advice

Is to take several identical parts at once, it is not only cheaper, but also relieves you of the need to re-order. Be greedy! For example, for my project you need a few Arduino NANO, when buying five pieces on the trade portals such as aliexpress.com or alibaba.com one piece will cost only $3.2 (2.7€). On Ebay 5 pieces of Arduino NANO will cost 3.3€ for one, but the delivery will be much faster.

Prices compare

The second advice

Be very careful when choosing a product on these trading portals – the product description is often very brief and uninformative. For example, you can buy cheaper the same Arduino Nano Atmega168P, but with another CPU (need 328P) which will very restrict you in writing sketches and applying in the project. Also apply this recomandations to modules of Bluetooth and Motor-drivers, compare the picture on my site and on the sites of sellers, they should be identical (in part because of this I bring pictures instead of diagrams).

Find details

The third advice

Buy from local vendors consumables (wires, connectors, etc.). Shops such as Radioshack are almost everywhere. If you look a little you will find that very often next to you there are private sellers of details of Arduino, it is slightly more expensive than on sites, but at times faster. Plus there will be communication, often people trade Arduino not for profit, but for the sake of a hobby (just like me).

All items for one URB unit bought in this way are for me a less than $4 or approximately 3€.

Local vendors

Comparison URB project with manufactured solutions

Now let's just count. I will compare the price of electronics, without wires and power supply blocks. I'm not so sure about real prices, but approximately in out June 2018 so:

Conclusions

I took the simplest set of parts for installation the electronics for "Symmetrical track plan" from the site of Horby. And it's not even a wireless console. The price difference with the same functionality eightfolded, this despite the fact that the expansion options for my project is much greater. The attempt to calculate the price of the necessary components from the Pro series from the company ROCO led to a difference of 25 times!

And for me it was a bit surprising that I did not find on these sites a classic set for DC control.

URB Project
Detail Quantity Price $ Price €
URB unit 2 4.00 x 2 3.40 x 2
Arduino NANO 2 3.50 x 2 3.00 x 2
Arduino Train Junior App 1 9.99 9.99
Servo SG-90 4 1.40 x 4 1.20 x 4
Relay 2ch 2 1.20 x 2 1.10 x 2
Bluetooth HC-05 1 2.80 2.60
Motor-driver L298 1 1.50 1.30
Total 37 34
DC control

All well-known manufacturers have ceased production DС control systems.

DCC control
Detail Quantity Price $ Price €
Hornby DCC Select Controller 1 139.99 121.99
Digital Locomotive Decoder 2 25.99 x 2 22.50 x 2
Hornby Accessory Decoder 1 52.00 48.99
Surface Mounted Point Motor 4 12.99 x 4 9.99 x 4
Total 296 256