# Teensy controller



## Shdwdrgn

I just ordered several pieces to start a new project today, and thought I would create a thread to document the progress...

The goal is to have a complete microcontroller on board each (HO) locomotive with several onboard sensors. Communication will be provided by bluetooth. This is an ambitious project because with an onboard computer there is the possibility of self-guided trains. Imagine if each loco could be given a set of directives -- go to point ABC, pick up three cars, and drop them off at point XYZ -- and the loco had enough sensory information to complete that task without any further guidance. This is the end goal, but there a huge amount of work to complete before I ever get near that point.

To actually make a loco autonomous, it needs to have a LOT of information available. First and foremost, it actually needs to know where it's at. I was thinking about using the LED track signals as information posts. You can create a self-clocking signal that has an average duty-cycle of 50% but contains a data stream. To the naked eye the LED would appear on, but a receiver could read information such as what marker number this is, and whether the track ahead is clear. Next, the loco needs to detect the load on its couplers so it knows when it drop or connects to other cars. It would also help to have a load sensor on the motor so the program could be given some understanding of grades and load weights, and be able to calculate the ETA for a certain run (and determine the speed needed to meet a given timetable?). And while we're at it, why not feed sensory data back to the main computer, such as track voltage in each section, which could be used as an indicator of when a track cleaning needs performed?

The first question some may ask is, why bluetooth? Well, for my particular needs and target hardware, this is a very easy and cheap solution. I picked up a slave module (HC-06) off ebay for less than $5. It has four wires -- +3.3v, Gnd, Tx, and Rx. You talk to it like a regular serial device, it even uses AT commands like the old modems. Plus every cell phone has bluetooth available, so the possibility exists to write a simple interface to control each train without having to buy expensive dedicated controllers. And bluetooth allows you to name the device, so each loco could be given a full identifier like BNSF4321 and you could easily find your target loco from a list. Bluetooth does have a limitation of a 40 foot range (at most), however my layout is only 12x12, so this is not an issue for me.

Since have to start somewhere, I placed several orders for hardware today. As I mentioned, I already have the bluetooth controller. The first component is a Teensy 3.1 microcontroller ($23 including shipping). If you're not familiar with this, it is the size of a wide 28-pin DIP, approx. 0.7 x 1.4 inches, and it is absolutely loaded down with I/O pins. There's standard digital lines, a large number of 10-bit ADCs, and a 16-bit DAC which can be used for sound. It uses the same chipset as some aurduinos, which means there is a huge library available of code and schematic examples. You flash your code through a regular USB port, then give it a 5vdc source and let it run.

Next up was a DC-DC converter so I could get a stable 5V off the rails. This is based off an LM596 chip which provides an adjustable output at 92% efficiency. I got a 5-pack of these for under $6.

And finally, to get things rolling I picked up a 10-pack of L293D chips for $5. This chip will allow the control of two DC motors. The computer can set the direction, and by using a PWM input I can control the speed. Now this chip is limited to 1.2A of output so I'm not certain it will be able to handle my older Tyco motors, but apparently you can stack two chips together to double the rating. They're cheap, so I'll play with the chip and see what happens.

Altogether, including a small circuit board for the motor controller, I should be able to assemble a unit that is about 13/16" wide, 1-11/16" long, and about 1-1/4" tall if I stack everything together. I'm not seeing any problems with fitting this into a loco. And for about $30 in hardware, there's a huge amount of potential here.

Unfortunately the DC converters and motor controllers are both coming from China (extremely cheap prices, but it takes forever to arrive). I also have a 100-pack of hall-sensors coming from China, which will provide more sensor data. Surprisingly though, the computer order not only gave me a tracking number, but the unit has actually been shipped out from the post office and is due to arrive on Monday! Once that comes in, I can provide power via the USB cable and start experimenting with the bluetooth. Once I can get a connection established, I have to write a framework for commands. Then I can start adding in pieces such as motor control and go from there.


----------



## rkenney

Sounds like a lot of fun. I assume this is an Arduino project? Here is a link to the blue tooth module:

http://www.instructables.com/id/Add-bluetooth-to-your-Arduino-project-ArduinoHC-06/

:smokin:


----------



## DonR

This is a very interesting project. I very much appreciate the
type of thinking that goes into designing controls such as you
propose. I've done complex controls using relays, but it would be much more
efficient as a digital system.

However, I also view it kinda as a SAD step forward.

If the trains are running themselves, actually throwing
turnouts, starting, stopping and moving cars from track
to track, then what is the operator to do? Just sit and gaze?

While the project is extremely creative, the end product would
be something that is not much different from watching
the same actions on a video.

I would hope that you would retain in your design the
ability to shut down the self controllers so you can
run the trains the old fashioned way.

So you understand where I'm coming from I still use
a Western Electric rotary dial land line and
a flip cell phone.

Don


----------



## Shdwdrgn

@rkenny - that is exactly the bluetooth module I have, and one of many pages describing how to use it. The teensy board is chip-compatible with arduino, so the same code will work but the pinouts would have to be adjusted. There is one possible issue I was reading with the HC-06 however: commands sent to it are interpreted 1 second after they come, rather than being terminated by a linefeed. This *could* lead to a problem with realtime control not responding fast enough, but I'll have to get the unit up and running to see what the real affects are. If this does cause a problem, the HC-05 is linefeed-driven and pretty much the same price.

@DonR - Personally I take great pleasure in watching a complex, well automated project run itself. And something this complex could easily take on a life of its own. With that said, I agree that sometimes you just want to take personal control of a train. That's why I mentioned the possibility of a simple interface that could be run from any cellphone -- the self-guided trains would still follow their normal rules of collision-avoidance, and the interface to your train would give speed/direction control plus a choice of potential upcoming routes so the turnouts could be thrown appropriately. There's also the possibility of viewing that train through on onboard camera... they're getting so small these days that it won't be long before we can mount one right in the cab.


----------



## rkenney

Please post us some links with how-to steps for those of us unfamiliar with the technology. We'll be interested to see your progress and results.

I'm rather like Don for most of my post-war trains. The fun of your project, like many, is in the doing/learning process more than the end result.


----------



## Shdwdrgn

I do plan on posting exact schematics and details as I progress. I'll set up a web page with the nitty-gritty details such as setting up the software to communicate with the teensy board, but I'll cross-post schematics here as well. If there's enough interest, maybe others can help me hash out a communications protocol and work towards some sort of standard for this type of project. I'm fully behind open-source projects and would love to see something come of this other than my own personal use.


----------



## Cycleops

I'm with Don on this one. Whilst it's awesome to watch a well automated layout it's not really something that would give me a huge amount of pleasure from doing myself. But as they say ".chacun à son goût".


----------



## Shdwdrgn

OK the first step is done, and it was surprisingly easy! I now have bluetooth communication between the Teensy computer and my cell phone.

For reference, I am also documenting things from my own web page: https://sourpuss.net/projects/trains/computer/

The first step was to get software loaded on my desktop so I could talk to and program the Teensy (see here). The next step was to put together some code that would show me when data was entered from either the serial monitor or from my phone. Once I got that working I added a small bit of functionality by allowing 0 and 1 from the phone to turn the Teensy's LED on and off. The final code can be found here. On my (android) cell phone, I installed a program called "BlueTerm+" which will connect to a bluetooth device and allow you to send and receive text from it. Note that the HC-06 does NOT use linefeeds, so you only need to type the character and wait less than 1 second for the information to be processed. (This also means I can't easily send complex commands through the phone.)

The next step was simple customization... I wanted to change the BT name from "HC-06" to something more meaningful. The HC-06 defaults to command-mode, then goes into transmit mode when you pair with it. To change the name of the device, pull the power on the Teensy and plug it back in. Launch the serial monitor from the arduino desktop program. The AT-commands are case-sensitive, so you MUST enter them in all upper-case. Start by typing "AT+NAME" in the serial monitor and clicking the send button. In a couple seconds you should receive the reply "OKsetname". This means you can successfully talk to the device and it is in command mode. Once thing I noticed is that BT does not like special characters in the name. For example, I cannot set "D&RGW13", but I am able to set "DRGW_13". Typically the underscore and hyphen characters are allowed in names, and this appears to be the case here as well. Once you set the name, try scanning for new devices on your phone. If you previously paired with the BT module already, it will continue to show the old name until the first time you pair with it again. You can also set or delete the pin number with "AT+PINxxxx" where the x's represent a 4-digit number. Leaving off the number will erase the pin.

So... I've proven I can easily pair up a phone with the new devices, and I can send data in both directions. I also have a very rudimentary control code in place to turn the LED on and off. I have a few other projects to work on from this point...

1) When the L293D controller chips arrive, I have a schematic ready to be tested to try running a DC motor. Then I will expand the current code to include setting the motor speed and direction.

2) It would be nice if the locos could read positioning data from the track signals, so I want to set up an older Teensy 2.0 to flash a code in an LED, and see if I can get the new Teensy board to pick up that signal and decode the data. If this works, it could be used in conjunction with the Hall sensors to let the primary computer mark a block as occupied.

3) I would like to use something like a RaspberryPi as the primary controller for my layout. I have an older one sitting here, plus a USB-bluetooth module. I need to begin working on the software on the Pi to control the Teensy. If I can automate pairing the bluetooth devices together, then setting up code to send signals to the Teensy should be easy.

*UPDATE* Here's a schematic for wiring the HC-06 to the Teensy 3.1...


----------



## 400E Blue Comet

That sounds amazing!
But robo-trains?
Be sure not to create Avengers 2: Age of Ul-TRAIN   



DonR said:


> This is a very interesting project. I very much appreciate the
> type of thinking that goes into designing controls such as you
> propose. I've done complex controls using relays, but it would be much more
> efficient as a digital system.
> 
> However, I also view it kinda as a SAD step forward.
> 
> If the trains are running themselves, actually throwing
> turnouts, starting, stopping and moving cars from track
> to track, then what is the operator to do? Just sit and gaze?
> 
> While the project is extremely creative, the end product would
> be something that is not much different from watching
> the same actions on a video.
> 
> I would hope that you would retain in your design the
> ability to shut down the self controllers so you can
> run the trains the old fashioned way.
> 
> So you understand where I'm coming from I still use
> a Western Electric rotary dial land line and
> a flip cell phone.
> 
> Don


Well if you want control of a train, you can have a "Classic" train on the layout. The rest of the trains would be the self-controlled trains. But the "Classic train" could be controlled by you. Mmm I can see a devious possibility of using it to mess up the self-driven trains. But anyway, I don't know if analog trains would work for this, since you need the track voltage for the self-driven trains. Using the transformer to control it would also effect the other ones. Maybe DCC? I'm not 100% sure of how it works, but I'm willing to bet it would work for the "Classic train" idea.


----------



## RT_Coker

Shdwdrgn,
Very interesting, especially to me. I have been working on something very similar for over a year now. I am doing open-source Direct-Bluetooth-Train-Control so you have my full encouragement. The first DBTC HO-FTA size boards are ”in shipping” and will be used for final testing and integration into a demonstration locomotive (that hopefully will work as designed). If you want, I can point you to a fledgling group doing DBTC. If not, that’s fine; you still will have my full encouragement.

The pursuits of new and different control ideas will only help hobby users and bring more (and younger) people into the hobby.
Bob


----------



## Shdwdrgn

That would be awesome! Even if I go a different direction, it's still great to see what kind of ideas others are working with. Honestly I'm glad to be working out the basics by myself because I learn a lot along the way (and I don't using my electronics degree nearly enough!) but for the software side it would be very helpful to know how other people build their systems so I don't have to repeat a lot of the same work.


----------



## RT_Coker

Shdwdrgn said:


> That would be awesome! Even if I go a different direction, it's still great to see what kind of ideas others are working with. Honestly I'm glad to be working out the basics by myself because I learn a lot along the way (and I don't using my electronics degree nearly enough!) but for the software side it would be very helpful to know how other people build their systems so I don't have to repeat a lot of the same work.


The group is not limited to one direction just DBTC.
Sent you a “Private Message”.
Bob


----------



## gregc

Shdwdrgn said:


> The goal is to have a complete microcontroller on board each (HO) locomotive with several onboard sensors. Communication will be provided by bluetooth. This is an ambitious project because with an onboard computer there is the possibility of self-guided trains. Imagine if each loco could be given a set of directives -- go to point ABC, pick up three cars, and drop them off at point XYZ -- and the loco had enough sensory information to complete that task without any further guidance. This is the end goal, but there a huge amount of work to complete before I ever get near that point.


While I'm sure developing an embedded processor module is interesting, I believe it will be difficult to debug the code on the embedded processor and be time consuming and inconvenient to update the code in the embedded processor.

Any locomotive with a DCC controller already has a picocontroller on board. I think supporting communication, motor control and sensors alone would tax most controllers that can fit within a locomotive. I also believe that to support the intelligence and data to do what you propose would require a relatively large amount of memory. Current draw will increase with processing speed and memory.

When I worked on embedded DSP systems, we probably spent just as much time building telemetry to debug the system as the system itself.

I would suggest that you continue to design and build the embedded system you describe, but limit the processing to only support the I/O you've described and put the intelligence in a PC. In other words, instead of using a PC (ipad, ...) as simply a GUI, implement the intelligence, data storage and GUI on the PC which issues commands to the embedded processor to control the motor and collect sensor data. The embedded processor becomes a slave to the PC. This also free resources in the locomotive to support more advanced sensors.

I believe developing the intelligence for more automated operation will be very complicated and much easier on the PC. The PC has more processing power and memory. The system behavior can change drastically by simply changing the application running on the PC. It would be faster and easier to update the code on the PC without touching the embedded processing in the locomotive,
once that code is stable.

the other aspect of more centralized control is that that intelligence can determine what to do based no only on the sensor data from one locomotive but from all. In addition, that same PC can control turnouts and signals as well as detect train position through occupancy detectors. While having the PC controlling/communicating multiple locomotive can avoid collisions, it could also support cooperative operation, multiple locomotives operating in the same area. You may be interested not in artificial but "insect intelligence".

One way to look at more self autonomous operation is that level of commands moves higher. Normal operation controls the direction and speed of a locomotive. That is done to pick-up or drop off a car, which is done to break down or create a train, which is done to move a train load of cars from one destination to another. I'm suggesting that operator no longer controls destination and speed, but which car to pick-up/drop off a car. The next level would be which cars and train, ...


----------



## Shdwdrgn

I agree that these little computers can't handle _all_ of the tasks. I'm thinking that the complex calculations like route-mapping and scheduling would best be left to the primary controller. But once the train knows which way to go, it just _might_ be able to pull off getting itself there.

The whole project will certainly have to be built up in stages. I'll start with the basics like collision-avoidance and tracking its own location, then build up to more complex tasks. And who knows? By the time I get up to the point of full autonomy, there may likely be microcontrollers available that DO have the processing power to handle the task.


----------



## gregc

have you thought about the coupling process?

how does the embedded processor in the locomotive know it has successfully coupled to the target car? is there a difference between the locomotive coupling to the car or coupling to a car attached to the locomotive? Is there a sensor that detects the impact/load or is it purely positional?

what about the uncoupling process?

how does embedded processor determine that the car is in the correct position? does the locomotive have a mechanism to uncouple on demand or is it relying on momentarily stopping over a Kadee uncoupling ramp?

even if the locomotive process is basically a slave to a human operator or PC, there are several advanced low-level operations that require developing sophisticated mechanics/HW/SW.



I'm working on controlling RF HW. It's interesting/satisfying to affect RF HW just with SW, without having to solder anything. I can do my work in my office with the target HW in a lab. Last week it was controlling GPIOs with tight real-time sequences and verifying those sequences with a scope accessed remotely from my office.

But every SW change requires 5+ minutes to recompile the code, erase the target flash and then reprogram the target flash. Making the development process productive means minimizing the reprogramming time. Maximizing the debug information minimizes the number of reprogramming occurrences.


----------



## Shdwdrgn

Regarding the coupling process, I was looking for options in this post. The real trick is just having some kind of bump sensor that triggers regardless if the loco is pushing 1 car or 20. That will be made even more complicated by today's low-friction metal wheels -- if the loco is backing up at a slow, steady pace, there will be very little 'bump' at coupling. That's why I'm looking into a more sensitive pressure detector, so hopefully I can at least determine the weight of the attached cars. Failing that, I will have to rely on track sensors, and simply back up until a car is detected near the end of the spur.

For decoupling, I'll be using under-track electromagnets. I'm thinking of having an IR LED detector centered over the decouplers. Each loco should have an accurate count of how many cars it is pulling, so the main computer can count the gaps in between cars and tell the loco when it is in position to decouple the appropriate cars.

I'm working with a MUCH smaller system here. It takes a few seconds to compile, and a few more seconds to flash the new code. The Teensy only has 256K of ram, so it doesn't take long.


----------



## gregc

sensing coupling is a non-trivial mechanical problem

while using various LEDs positioned in the track is a doable way of determining local position, it can become a logistics problem if many LEDs are needed and differentiating between them.

is there a more general solution that can determine position anywhere on a flat surface?


----------



## Shdwdrgn

The decouplers I have planned are staggered enough that the LEDs won't cross over each other, so that's not an issue.

For sensing trains in other locations I plan on using small magnets an hall sensors. I'm waiting on a shipment from China right now, and if they work out they'll be dirt cheap -- 100 pieces for $10. This one in particular is an A3144. The range is based on the strength of the magnet, and I just got in a pack of 1x3mm rare-earth magnets to test. I've seen reports of around 1 inch with ceramic magnets, which should provide plenty of time to sense a speeding train.


----------



## nemofreed

It would be awesome to see the cab view in a tablet with a HUD feeding info to the operator. 

Operate your layout on a long flight. Sounds brilliant.


----------



## RT_Coker

Shdwdrgn said:


> The decouplers I have planned are staggered enough that the LEDs won't cross over each other, so that's not an issue.
> 
> For sensing trains in other locations I plan on using small magnets an hall sensors. I'm waiting on a shipment from China right now, and if they work out they'll be dirt cheap -- 100 pieces for $10. This one in particular is an A3144. The range is based on the strength of the magnet, and I just got in a pack of 1x3mm rare-earth magnets to test. I've seen reports of around 1 inch with ceramic magnets, which should provide plenty of time to sense a speeding train.


I am temporarily using a magnetic-read-switch, but don’t consider this a good long term solution. I will be very interested to hear how the hall sensors work out.
Bob


----------



## Shdwdrgn

I can tell you for a fact they *will* work, it's just a matter of finding the right one for the job. In this case, one that has enough sensitivity to work with magnets which are small enough to not cause the cars to 'stick' in unwanted positions. The magnets I got yesterday are to be used on the clamshell doors of my old Tyco hoppers, and a quick test showed that these small magnets have plenty of strength to open the doors. This places four magnets up to 1.25" apart, so ideally I need a hall sensor that will detect the passing of these magnets as a single event. (For reference, a hall sensor can also be configured as an analog signal, so the computer could read the passing of a magnet as a wave of magnetic strength, but for our purposes a simple on/off trigger will suffice.)

I have a degree in electronics. I sucked at the analog stuff, but I'm great on the digital side. For our class final we put together a large project that culminated in filling several train hoppers with shredded paper. For this, we used a hall sensor under the track, and a small ceramic magnet glued to the bottom of each hopper. The computer was programmed to detect when each hopper was in place, stop the train and fill the car, then advance to the next car, until no more hoppers were detected. I did the programming and essentially when I got the signal that a magnet was detected, I kept the train running for another X milliseconds to an estimated 'centered' position under the paper bin before stopping the loco.

The head of the A3144 hall sensor is 3x4mm, so it will easily fit between two rails of an HO track, and it is not affected by paint or even a light sprinkle of ballast. It's a non-mechanical solution, so it won't wear out over time and has an instantaneous response. This model was specifically chosen because of the very low cost, and because it is made for automotive applications and will not get out of adjustment due to temperature swings (my layout will be in the garage, so this is important to me). So the only question left is in hooking it up and confirming the sensitivity to the magnets I'm using.


----------



## Shdwdrgn

Well that was disappointing... Got in the first part of my order for the A3144 hall sensors and hooked one up. I can't seem to get more than about a 3/16" range out of them. I've tried at 3.3v and 5.0v, various values of resistors from 1k to 22k, with and without a decoupling cap across the power lines. It doesn't even seem to matter if a use a single weak ceramic magnet or the whole stack of rare-earth magnets. I even tried hooking it up to an analog line on the Teensy, but it still just reported like a switch.

So I'll have to dig into this more and see if there's something I can to increase the sensitivity. In the meantime, if anyone has any suggestions, I'm open. The circuit is really basic -- just a resistor between the V+ and output lines. I just expected this device to have about 5x the range.


----------



## gregc

Shdwdrgn said:


> I can't seem to get more than about a 3/16" range out of them. I've tried at 3.3v and 5.0v, various values of resistors from 1k to 22k, with and without a decoupling cap across the power lines. It doesn't even seem to matter if a use a single weak ceramic magnet or the whole stack of rare-earth magnets.


the 3144 datasheet indicates that the min supply voltage is 4.5V. 5V is ok, but 3.3V shouldn't.

The figures on pg-4 indicate that it's sensitivity should not depend on supply voltage, as long as it is w/ spec. 5V should be enough.

The data sheet also indicates that the 3144 has wide range of magnetic switch points, 70 - 350 gauss, while the 3141 has a lower and tighter range 50-160. Could you have one (or a batch) that switch at a relatively high level (e.g. 300). try several others.



Shdwdrgn said:


> The circuit is really basic -- just a resistor between the V+ and output lines.


it is a 3 terminal device(?), requiring a supply voltage on pin-1 and has an open collector output which is observable by tieing pin-3 to supply through a resistor. Presumably the output pulls to ground when active.


----------



## Shdwdrgn

Ugh the specs seem to be all over the board, depending on which company's datasheet you pull. Another sheet I found said the range was 35-450G, but the original specs I was looking at suggested a much tighter 35-70G for the trigger. I'll have to look around some more to find another possible model that is still really cheap.

One suggestion I found to increase the sensitivity is to place a piece of steel behind the sensor. This actually gets me out to a full 1/4", but it's still nowhere near my preferred range.


----------

