# It's Alive!!!



## Shdwdrgn

Just wanted to share that today I made the first baby-step. I put together an arduino with a voltage regulator and bridge rectifier, attached to the motor of a loco with an L293D controller chip. My first bit of code cycles the motor between zero and half speed, then back down again.

It's not pretty. The track has been in the attic since 1993, and sat in my parent's garage another 10 years before that. The loco was an old find from ebay and still needs some cleaning. All power to the circuit relies on the loco making good contact with the track, but I did add a 4700uF capacitor to smooth it out. Still a lot of work to be done there...

The good news is that the train performed exactly as desired... it ramped up to speed, held for a couple seconds, then slowed down to a stop. BACKWARDS. Oh well, I had a 50/50 chance of that happening. Time to add some directional control.

I had to head in to work after that, but I ran into one stumbling block -- When I reversed the direction in the code and tried to re-flash the arduino, my computer was not able to make a connection to the USB port. After some research, it appears the USB control is handled within the code block, and if you program does not have suitable pauses, the USB code never gets a chance to run. Long story short, I think the solution is in doing a reset as I'm starting to upload my code, which should give the arduino a chance to respond.

Once I get this problem figured out, the next step is adding code for the wifi module and start setting things up so I can send commands over wifi for speed and direction. Then I have to figure out how to miniaturize everything to fit inside this little HO 0-4-0 and tender.


----------



## gunrunnerjohn

You need to have a delay when you initialize before you start beating on the ports. That gives the loader enough time to seize control before the program takes over the ports.

Don't ask me how I know this.


----------



## gregc

doesn't the arduino have a 2nd processor which has the USB interface to the PC and is used to program the user processor. Since it's a separate processor, why would the user code need to do anything to support re-programming?


----------



## Shdwdrgn

Greg - No, this is a pro micro board with an atmega32U4 chip. Everything is all built into the chip.

I managed to get the board re-flashed with some new code and have been playing with it. Took me a bit to figure out, but for this motor controller I need to be able to PWM *both* of the control pins. Essentially one pin makes the motor go forward and the other pin makes it go backwards. So I have to make one wiring change -- moving the controller wires to a different pair of outputs so I have pwm on both of them.


----------



## Shdwdrgn

So apparently the 'delay' command in arduino is evil... it stops everything, including the USB bootloader code. I found some examples of using the built-in timer to allow the code to continue running, then fork when it was time to do an update of the motor, and now I am able to flash new code every time without any acrobatics.

Right now I'm running a small script that runs the train up to 3/4 speeds and back to zero, then reverses up to 3/8 speed and back down. It just keeps doing this loop over and over, nothing too exciting, but it does make for a good test of both the loco motor capabilities and the track. I tore the loco down to the wheels again today and cleaned the wheels and electrical contacts, plus removed some hair from the axles. I also wiped down the track with alcohol, so overall things are running smoother. I started adding cars and found that this little 0-4-0 can start spinning its wheels without much load. It also has a horrible time keeping electrical contact. Since I'm going to be putting metal wheels on the tender when I get one, I decided I should add more pickups and maximize the available electrical paths. This track is about as worse-case scenario as it gets -- even though the top of the rails is somewhat clean now, all of the rail joiners also corroded, so there are problems all around. And yet, I've been able to let the train run for several minutes at a time between problems, going back and forth, and the speed changes are nice and smooth. Maybe when I get the extra pickups working on the tender, I'll chuck one of the drive wheels in the lathe and cut slots for some traction bands.

Anyway, despite the electrical difficulties, I'm having fun with it. Hopefully over the long weekend I can try to get the wifi code added in. I should also work on adding more capacitors to filter the electrical going to the computer board. Wheeeeeeee


----------



## Lemonhawk

In the world of real time programing, waits are deadly! There is some sort of multi-tasking library you could check out. Back in the 70'same we never had enough processor power so anything that could be pushed to run in back ground was leaving just the necessary stuff for the foreground.


----------



## Shdwdrgn

I prefer using the timers anyway. Once I start adding more to my code, different sections will need to fire at different times, so the delay would be inappropriate anyway. As this project expands, I'll have to keep my options open for which board to use. The arduino pro micro has 32k of flash and 2.5k of ram, while the teensy has 256k of flash and 64k of ram, but the teensy is also 4x the price (still only $20 though). I may need that extra space for the program I have in mind, but we'll see how it goes.

One thing I'm thinking of changing for space considerations is the voltage regulator. The one I'm using is a fairly large beast (larger than the arduino), however all I really need is a fixed regulator that can drop 18V down to 5V. A basic 7805 can handle a whopping 1.5A, far more than I need, and for my low current requirements I doubt it will even warm up. I'm pretty sure I have one kicking around here somewhere. If that works out, then the filtering capacitor will be the largest single item, and I should have no trouble fitting everything inside the tender.


----------



## bluenavigator

Arduino UNO is fairly easy to use and nice additional to be applied to control the locos. I would recommend to get MEGA version so you can add more relays to control connections on each set of isolated tracks. It is possible to make it to act like DCC control module. 

That is what DCC control module based on but with signals being sent via tracks to the locos' decoders.


----------



## gregc

Lemonhawk said:


> In the world of real time programing, waits are deadly! There is some sort of multi-tasking library you could check out.


doing work inside a periodic interrupt is one approach for having two independent tasks/processes/threads


----------



## Shdwdrgn

@bluenavigator -- that is way too large to fit inside an HO scale loco, and for the main layout controller I'd rather have a full-blown computer like a raspberry pi or an odroid.

I've also been playing with some attiny85 boards which are less than 3/4" square (including the usb port for programming) and at less than $2 each, would be great for small tasks like track signals. The goal here is to use manchester-encoding of the track signal LED's to pass data about the block number the loco is in and occupancy in the tracks ahead, which the loco should be able to pick up as it passes the signal.

@gregc -- I'm not sure these chips have interrupts, but if they did it would certainly be a good method for certain tasks. However I would think something like motor speed control isn't that critical to be performed at exact times. At the moment I'm only checking the speed every 100ms, so there's plenty of time to perform other tasks in between.


----------



## gregc

Shdwdrgn said:


> I'm not sure these chips have interrupts, but if they did it would certainly be a good method for certain tasks. However I would think something like motor speed control isn't that critical to be performed at exact times. At the moment I'm only checking the speed every 100ms, so there's plenty of time to perform other tasks in between.



it's hard to imagine a processor without interrupts. Looks like the AT mega640 referenced on the Arduino Mega 2560 page has interrupts. 

And while they can be used for more precise repetitive tasks, I was simply suggesting that they are a way of running two independent threads of control instead of having even a simple scheduling loop that may use delays to wait to perform actions. Some processors can even sleep between interrupts.

if the motor controller runs in the interrupt, the main thread may need to do very little, allowing USB access.


----------



## gunrunnerjohn

My first function I code is the timer interrupt processor for my timers. I can't think of anything I've programmed that had any substance that didn't have multiple timers running.


----------



## Shdwdrgn

Interesting... It's funny, after all these years of working on computers I've never actually used a proper timer. I'm betting it's one of those things where once I start using them, I'll never go back. 

I just ran to the hobby shop and picked up a pack of new rail joiners. I'll just swap out all of them and see if that makes things run smoother. It's really a pain to try working on code when the computer keeps resetting every few seconds...


----------



## gunrunnerjohn

I'm not sure how I'd program without having a timer block! I normally code my "standard" block of either 1ms or 10ms timers, and if I need longer periods, sometimes I add some 100ms or 1sec timers. They're all count-down timers, they simply count to zero and stop. Usually, in my processing, I just check if a timer has expired and deal with the event at that point. Most of my stuff ends up having a similar structure for the most part. Why fool with perfection!


----------



## gregc

Shdwdrgn said:


> Interesting... It's funny, after all these years of working on computers I've never actually used a proper timer.


the difference between application SW on top of an OS (Microsoft, Linux) vs. embedded real-time firmware (assembler, VxWorks). But today, Linux runs on embedded processors.

one of the first features discussed in the XINU book by Doug Comer, (pre-Linux) is using a single timer (e.g. 1ms) and a linked list of events to be processed. It describes how to manage the list to add and process multiple events, some occurring at the same time. The first event on the list counts down the number of clock tics to that event and is replaced by the next event on the list which starts with a count of timer tics from the preceding event. Subsequent events are in terms of clock tics from the preceding event.

The point is that only a single HW timer is required to support as many timed events as needed. Of course the timer can generate an interrupt which performs the above processing which may only manage semaphores pending on the timed event. No need for delays nor more than one timer.


----------



## Shdwdrgn

I guess what I'm doing now is just a simple software timer. The arduino has a timer that tells how many ms since it was turned on. I'm simply setting a variable that says if the timer has passed this value, run this section of code. I have this feeling if I let it run long enough, though, the timer would loop back to zero and none of my blocks would be called after that. So yeah, a hardware timer would definitely be more appropriate for long-term.

It turns out setting up the wifi is more involved that I thought, but also much simpler to use once it is running. The esp8266 apparently has a full processor built in, which means I upload code to it to specifically connect to my local wifi, and it handles everything from there. So the arduino doesn't need to do anything except end and receive commands through the serial port. This leaves a lot more space than expected on the arduino for my own code. I just have to figure out how to get the 8266 set up first...


----------



## gunrunnerjohn

You can program a timer checking routine to detect and manage wrap-around when the timer overflows in your simple scheme, that's pretty simple.

The timer that Greg describes is what I use. There is a single timer interrupt that services all the timers. You can have as many as you like and at any desired rate. Typically, I do very little processing in the timer interrupt, it's just to service the count-down timers and set the completion semaphore to alert the external process that the timed event has completed.

Of course, there are other interrupts in many applications, but timers are a basic capability that you will use in virtually any application.


----------



## bluenavigator

Oh, now I get it. UNO inside the loco. I apologize for misunderstanding.


----------



## Shdwdrgn

Erg, my eyeballs!!! Been working on the wifi module since yesterday, and finally have some code working properly. Basically the arduino on the loco is initializing the wifi connection, then sending a "ready" message to the server. The server is receiving this, and after a short period the server sends a message back to the train. The data is being received on both sides (although I still need to get the arduino to parse out the info sent to it), so all the aggravating work of figuring out HOW is finally done. After dinner I'll see if I can finish up some test code, and hopefully be able to send commands to control the speed of the train on the track.


----------



## gregc

Shdwdrgn said:


> Basically the arduino on the loco is initializing the wifi connection, then sending a "ready" message to the server. The server is receiving this, and after a short period the server sends a message back to the train.


I realize you're just getting started and getting two-way communication is a big step. Congrates.

But I think you're going to want the loco/thottle to be prepared to receive data, not initiate communication by sending the first message. You'll want the PC or whatever device communicating with the loco to to send the first message and for the loco to respond. (Remember, there could be multiple locos waiting to be controlled).

And you may want some type of keep-alive or heartbeat so that the loco is sure it is still in communication with the PC so that if communication is lost, the loco comes to a stop.

I'm curious, if this is WIFI, how are you assigning IP addresses?


----------



## Shdwdrgn

IP addresses are assigned by DHCP like any other devce. The wifi ssid and password are programmed in the code, and as the loco gains access to the network it sends the signal to the listening server. I could have it send anything, such as identifying the loco number. 

This is also the reason why the loco has to reach out first -- on a network where the IP address can be anything, how can the server reach out to the loco without previous knowledge of the loco's IP address, or that the loco is even turned on? Doing it this way, when the loco is placed on the track it can reach out and say "here I am, give me something to do."

The great thing about a server is that multiple people can use it at the same time. There's not a strict 1-to-1 communication, every loco on the layout can send at receive messages. As I expand the server-side code, I will have it remember all the locos it has seen, which can be handy for such things as sending a panic 'stop' command to everything on the layout.

The idea of a heartbeat signal is also in the works. Last night after I got the loco running and receiving random speed commands, I started working on such a thing. Basically if the loco hasn't heard from the server in the past 5 seconds, it would begin slowing down to a stop. Unfortunately I started running into some generic problems with the code and wifi, and was too tired to figure out what I can done wrong... Once I get the problem corrected I'll get back into adding features. So far I've used about 43% of the programming space (12k out of 28k), but once the code is working I'll go back through and see what I can strip out and clean up to make it tighter.


----------



## gunrunnerjohn

Clients normally make the first contact with a DHCP request for an IP address. My question would be, how are you programming the ID of each locomotive? You need to have a specific name to know who's asking for an IP address.


----------



## Shdwdrgn

I figured at some point I would add in a way to identify the loco. If nothing else, each wifi connection will have a unique MAC address that I can associate with a particular loco on the server side.

At the moment I'm still fighting with the code. As I'm adding more, the wifi connection is getting unstable, so I'm having problems getting reliable send and receive. Gotta fix that first before anything else.


----------



## gunrunnerjohn

I didn't think you were ready for that step, I was just curious if you had thought about it.


----------



## Shdwdrgn

Whew! After much struggle through the weekend I was finally able to make the code run stable. Working with the AT commands is a royal pain!

So after banging my head on that problem (I'm stubborn that way), then I started looking into some of the other info I had found. Turns out there's a library for the esp8266 in the arduino coder, and if you use that you can quickly connect to a wifi and send/receive information without using the AT commands at all... It took me most of Sunday to get it figured out and rewrite my code (mostly lack of working examples), but I now have custom code on both the arduino and the esp8266, with a huge amount of free space on the 8266.

And if anyone is scratching their head, YES, the wifi chip is actually a full-blown processor, with a minimum of 512K of flash (which blows away the arduino I'm using with only 28k of flash). Even the original version I'm using has two free I/O lines available, so I've started offloading some of the processing to this chip. I have a couple more hardware problems I want to work out -- sensing how many cars are connected to a loco, and receiving data from the track signals so the loco knows if it needs to slow down or stop. I'd like to have the wifi chip handle the track signals, plus use the extra storage space to hold route information so a loco can get to its destination by itself. The signals will tell the loco where it is at and allow for passing on sidings, but the routing info will have to wait until I actually something more than a circle to test on.

Anyway, the code is working great now. Left it running for a few hours yesterday evening, and not even a hiccup. I'll be picking up components tonight to rebuild the whole computer into the coal tender, then I can start testing on the track again.


----------



## gunrunnerjohn

Cool, we look forward to seeing progress on this one.


----------



## Shdwdrgn

Well I got the parts and tested all the changes, but I think I missed something. I have proper voltage going to the computer and it is responding, however the motor driver ship is overheating quickly and I'm barely getting any current to the motor. I'll have to check my wiring tomorrow and see what I screwed up.

The original circuit has a 4700uF cap on it for power storage, but now I've done better. I found some fairly small 3300uF caps and I can place three across and still fit inside the tender shell. So that gives me 9900uF, which I think should give me almost 1 second on the computer. If I use a pin to sense the track voltage, I could probably send out a warning over wifi before power is lost.


----------



## gunrunnerjohn

Sounds like you may be driving it in more than one direction at the same time.


----------



## Shdwdrgn

I drew up an image of the hardware I'm currently using for this project.


The arduino is a pro micro 3.3v. When applying the 5v signal to the raw input, the voltage is dropped and able to supply 3.3v to the ESP866.

The LM7805 and L293D both require heatsinks.

More electrolytic capacitors can be stacked to provide a larger buffer -- on an 0-4-0 the pickup is pretty dirty and frequently resets the computer if capacitors are not used. _(Make sure to observe polarity!)_

I connected both sides of the L293D to double the current capacity. Together the chip can supply a full amp to the motor.










The components fit pretty well in HO, but if I had to I could move the bridge and 7805 into the loco. I'm still hoping to get some wipers made for the tender wheels, but I've been too busy working on the computer setup to take a look at that yet. I should probably add a small filter cap across the 5v line on the L293D to reduce any noise from the motor, but so far it hasn't produced any problems.


----------



## Shdwdrgn

Hmm it occurs to me that I previously had the filter cap across the 18v side (that cap was too large to fit in the tender though). I wonder if the 18v signal by itself is too noisy to allow the L293D to work correctly? Not likely since that chip is purely logic gates, but other than changing my voltage regulator that is the only change made to the wiring. Otherwise the problem has to be in the software, or I crossed something when I redid the wiring last night.


----------



## bluenavigator

L293D should be able to handle up to 36V output with the current up to 600mA. I am not sure which one that you have.

It is not exact "purely logic" gates but it is TTL compatible. It is a driver chip.

You might need to check this datasheet to get insight on this chip.

L293D Datasheet


----------



## Shdwdrgn

Right, it will handle 600mA on each side, but if you combine both sides together it will handle up to 1.0A (not 1.2A). That should still be plenty to handle HO motors, and it is a pretty cheap chip to play with.

I'm not seeing anything out of place in the wiring, and I confirmed the motor itself wasn't binding, so I'll have to break out the voltmeter.


----------



## Shdwdrgn

Well either something is wrong with the wiring or the 7805 may be bad. At the moment when I have 17v on the track, I'm only measuring 7.5v across the input pin of the 7805. All that voltage seems to be getting converted into heat in the L293D (which makes it odd that the wire carrying that current isn't also getting hot). I'm getting ready to desolder the power wire and see what happens with it.

I did find some missing code which sets the PWM pins to output, but considering the motor was trying to spin, I'm guessing that is the default state. I did load up an older program that I know works, and got the same results.

In the meantime, I've been working on the server-side code. I have the server component that talks to the locos, and I wrote a quick program that simulates a loco with various responses. I also have a web interface that shows the state of the trains it knows about, and when one becomes ready you can click it and take manual control. I just have a simple slider for the speed plus forward and reverse controls. The arduino code currently does a smooth transition between speeds, but I need to eventually add code so that if you tell the loco to change directions, the speed drops to zero before reversing.

My idea behind the server code is that having the loco controlled by a simple web page means you can do it from a laptop, a cell phone, or whatever you have handy. And it is a LOT easier to maintain a web page rather than dedicated apps for multiple devices.

Oh, I also added an identifier for each loco. Each wifi chip has its own MAC address, so I'm using that as a key. The server stores the mac address until you give the loco a name, and no matter what IP address the loco gets when it comes online, the server will still recognize it by that key.

OK, soldering iron heated up while I was typing... Removed the power lead to the L293D, and now I have about 12 volts across the 7805, and 13.3v across the track when the train is sitting on it. The diodes are likely dropping the 1.25v feeding in, but something is obviously wrong in the L293D. I'll have to start removing leads and see if a wire is shorting, or if I simply fried the chip.


----------



## trains galore

Check that the 7805 regulator is outputting 5v, I had one burn out (they ALWAYS do if you get the polarity wrong, trust me), and allow a full 12v to get to the L293d H bridge chip which burnt it out since the actual chip should run off no more than 5v (on the VSS pin) if I recall correctly, although it can switch larger voltages to your motor.

Sounds like an interesting project by the way! 
Also you can save yourself some hassle by getting an IC socket for your L293D so that if it does happen to burn out you can easily replace without re soldering it all over again!

You can also get a pre made l293d ''shield'' designed for use with robotics projects and arduino for quite cheap that you could use with anything really (including the other micro controllers like the Picaxe or Raspbery Pi) but it sort of ruins the fun of making your own! :smilie_daumenpos:


----------



## Shdwdrgn

The 7805 is putting out roughly 4.9v with everything connected to it. I've seen several pre-made boards for the motor drivers, but they're all too big. Using the bare chip gives me the smallest package. Also keep in mind this chip needs a suitable heat-sink on the ground pins, and I would worry about all that heat transmitting through a socket. What I'm doing is folding the ground pins over the top of the chip, and the other pins are folded underneath. Then I can solder some large copper wire across the grounds and connect the copper to the weight plates.

I mentioned I wrote a program to simulate a loco with my arduino code, and I've been playing with this today. It gives me a way to test new ideas, and this one took a bit of work to get right. I'm basically creating a arc for the speed control without using any cpu-intensive calculations. So when a new speed command comes in it starts increasing the speed by 1 point, then 2 points, etc until it reaches a maximum value, then it continues increasing at that rate until such time when it needs to start decreasing the rate of change. What this amounts to is the speed is changed in a smooth progression until the target speed is reached. If I am running at 3/4 speed and I tell the train to stop, it takes about 11 seconds to come to a halt, which should give the train more of a sense of 'mass'. (I will of course add an emergency stop button on the web interface.)

I think I've worked out the bugs between the web interface and the server program so tonight I'll try replacing the L293D chip and get my loco running on the track again, then see how all the new programs work on a live train.


----------



## Shdwdrgn

I completely replaced the motor driver chip tonight, but still had the same problem. This leaves the voltage converter as the only possible culprit, but I didn't want to swap it out tonight. Instead I wandered off to work on other things, and of course it hits me... This 7805 is only rated for 500mA. The motor chip draws up to 1.2A by itself! And that also explains the voltage drop I saw across the 7805 when the motor was trying to run. So this weekend I'll try to find a higher rated regulator and see if everything is happy then.


----------



## Lemonhawk

You mentioned attaching the ground wires to "weight plates" for heat sinks, are the "weight plates" isolated? Just a thought.


----------



## Shdwdrgn

Yeah the body of the car is all plastic. Also I use Kadee wheels which are metal, but have a plastic axle, so there's not much chance of picking up track current from anywhere.


----------



## Shdwdrgn

Got some 1.5A 7805's ordered off ebay this morning, and digging through at lunch I discovered a really tiny dc-dc buck converter that will likely work even better (I know the 7805's will put off a lot of heat). This converter I found is 17x11mm, takes an input up to 23v, has an adjustable output, and can supply up to 1.8A. Coming from China, but they're only 82 cents a piece (I ordered 4). The original dc-dc converter I had worked great for driving the computer and motor, but the entire unit was larger than my computer, wifi, and motor driver chip combined.

Well, it may be a few weeks before I'm able to properly pack the whole computer into the coal tender, but at least I won't have to worry about heat now.


----------



## gunrunnerjohn

Beware of the ratings of the eBay modules, those are absolute maximum ratings. I use a variety of these converters, but I'm realistic about the maximum output power.


----------



## Shdwdrgn

Yeah, I agree, especially with the chinese electronics. However realistically I only need around 1.0A of juice so the higher rating should give me some leeway. I had been looking for smaller units, and you would think a fixed 5v output would be easy to come by, but the units I had previously found only accepted an input of 15vdc. Of course I could drop that down with a few diodes, but I'd rather just use something that gives me what I need in a single step.


----------



## Shdwdrgn

One of the things I've really wanted to add to my computer-controlled layout is a camera in each loco, allowing the possibility to "ride along", but the small scale needed for such a feat seemed to be pressing the limits, and I thought I might have to wait for technology to catch up to my dreams. Well fear not, tonight I discovered a camera module that fits the bill!

The OV2640 CMOS camera module can be found on breakout boards, and I found at least one source for the module itself without anything wired to it. The module is only 1/4" square, uses a manual focus lens (which for scale viewing shouldn't be a problem), and has a 2-wire serial output among other options, which would allow the camera to be wired up to an arduino using only four wires. And there are already examples for using this module with an arduino.

The module actually supports up to 1200x1600 resolution @15fps, however the slow speed of the arduino greatly limits how much video can be processed. Personally, I would be happy to get a live 320x240 image on the web interface controlling each loco. With this kind of possibility available, the only real question becomes -- do I want to mount the camera in the nose of the steam loco, or put it back in the cab looking out over the boiler? Regardless, I'll be putting in an order so I can play with one of these!


----------



## bluenavigator

I would go with the camera on front! Rearview can come up later, that is after debug the program onboard.


----------



## 2869ral

I am very interested in this. I have always thought of myself as being fairly smart, but you guys have my head spinning! lol i know these electronics can do a lot of things for us and im trying to be a participant here because i want to learn and use this stuff, but WOW you guys are out of my league here. I will just keep trying to follow and ask a lot of questions if you dont mind.? Thanks Ron


----------



## Shdwdrgn

For what it's worth, while I have been doing programming for a very long time, I am new to the arduino world. Check my other thread about starting an arduino how-to class, I would love to hear feedback on what type of information would be most helpful to you.


----------



## 2869ral

Shdwdrgn said:


> For what it's worth, while I have been doing programming for a very long time, I am new to the arduino world. Check my other thread about starting an arduino how-to class, I would love to hear feedback on what type of information would be most helpful to you.


I already replied to that thread, and yes i am interested. Thanks


----------



## Shdwdrgn

Yep, sorry, I hadn't seen the replies to the thread yet.


----------



## bluenavigator

Actually, not every member know how to use Arduino but have some kind of knowledge toward model railroad in any scale.

Arduino is actually easy to use as long as one know basic C/C++ and equivalent programming.


----------



## Shdwdrgn

And there's so many example available online that for simple tasks you barely even need to understand programming.


----------



## Shdwdrgn

Here's a screenshot of the web interface I'm setting up. It does work directly with the arduino, although obviously the camera view is still a mock-up. The slider shows both the speed you set and the actual speed of the loco (the triple-bars on the left), updated three times per second. I also plan on having the trains read track signals, so I added a display for that. The MPH reading is based some numbers used to control each loco's speed, this one tops out at 168mph with is actually 3/4 throttle, but there will be a way to scale the output later for those that want to actually take the measurements.

This weekend I'm going to tear apart my arduino circuit and start rebuilding it until I figure out why it's not running the loco now. It's all fun playing with a web interface, but I want to actually control the train now and see how the response time is!

[EDIT] Oh, I bet you want the pictures too!


----------



## gunrunnerjohn

That's pretty cool, can't wait to see how this turns out.


----------



## Shdwdrgn

Most of the code is straightforward, although the rapid timing desired to show the info is a bit stressful on javascript under firefox. The camera code is where I'll really have to fine-tune the output to get a nice display, and video is completely new to me so it will be a challenge. I'm going to keep the video size small, probably something like 320x160, and if I can get at least 5-6 frames per second then it should be usable. Ideally I'd like to get that closer to 15fps at 640x320 for a really sharp output, but first I have to be able to just get a picture...


----------



## gunrunnerjohn

I suspect once you get any picture, improving it will be easier.


----------



## Shdwdrgn

I FINALLY figured out the problem... The motor is pulling quite a bit more current than I initially measured, peaking at nearly 2 amps at times, but running a little over 1A. I have this feeling the motor is lugging down, probably indicating a need from some fresh oil, however because of the draw I believe it has been frying the L293D driver chips. I started investigating because I noticed the chip was getting hot even with both control lines pulled low (this should mean a dead stop with no current flow).

Easy solution, and commonly mentioned online, I stacked two chips together. I kept an air gap between them, and fed some stranded wire between the grounds, then once soldered in place I unwrapped the strands to make a better heatsink. I also decided to add a third wire to the enable pins. So I have two wires that get set to low or high depending on the motor direction, and the third wire now controls the speed. This was done just in case there's some cross-over between the two PWM lines I was using before. The arduino has plenty of free lines, so using another pin doesn't hurt anything.

With the proper current-handling in place, the motor is responding smoothly, and practically no heat at all. I _think_ what happened is the previous chip shorted across one leg of the internal transistors, so it was constantly pulling full current even when the other legs were driving the motor forward.

Now that this issue is finally resolved, I can spend some time working on the first part of the arduino class and try to get that going....


----------



## trains galore

Maybe you could control some small 5v relays with the L293d and use those to switch the motor, relays draw far less than any motor will! 

Very tiny ones are avaible that would easily fit.

You would need at least two though, one for direction and the other to start/ stop power to the motor.


----------



## gunrunnerjohn

Here's a 2A DPDT 5V coil relay I've used a lot. You can also get the same form-factor in a 5A contact version. It only requires 10ma coil current, you can drive it from a standard logic output.


----------



## Shdwdrgn

Relays are only good for turning the power on and off, you can't use them to control the _speed_ of the motor. The L293D is essentially a set of four solid-state relays which allow control of the direction, and when you pulse them on and off really fast, you can control the speed. For example, at 25% duty-cycle, the motor will run at 25% speed, but because each pulse is sending the full voltage to the motor it has a lot of power even at lower speeds.

Another thing to consider is that since there is almost no heat when the chip is running properly, the motor is likely not pulling much power at all under normal circumstances. I think what is happening is the motor is surging in certain instances, and after a few times of that it was blowing the single chip. Now that I've doubled the current capacity by using two chips, it can handle those surges.

Here's a couple of shots of the mess that is my current circuit. I have a lot of work to do to get it to fit inside the tender shell.









And here's a close-up of the doubled L293D chips.


----------



## gunrunnerjohn

I realize the limitation of relays, just figured I'd give you a source if you wanted them. 

Why not use a more robust chip?


----------



## Shdwdrgn

Honestly, because I haven't found anything else that is as easy to use and as cheap. I was doing some searching over the weekend, but chips that handle somewhere in the 1.5 to 2.0 amp range are running about $7 or more and generally require huge heatsinks. I'm getting the L293D for 40 cents each, and even stacking two of them together doesn't take much space (and is probably only needed for these ancient motors). However if you have some part numbers to throw my way, please do... I'm sure I missed a lot.


----------



## gunrunnerjohn

I don't have part numbers, but there are many motor driver modules on eBay for peanuts, perhaps one of those would be useful?


----------



## Shdwdrgn

The problem with the modules is that they're too large. They usually have easy-to-use screw terminals and a large footprint to make them convenient to work with, but when you're trying to cram them inside an HO train you don't have room for all that. However I have taken note of the various chips used by the ones I found, and most of them are lacking. One of the more popular ones tops out at 800mA, and many only support up to 12V or 15V.

The specs on the L293D are 5-36V, and 1A per chip. They also have flyback diodes built in and so far there hasn't been enough noise from the motor to require filtering caps across the chip. Even though I'm using two of these chips to meet my current requirements, it's still hard to beat the cost, space, and simplicity of using these in the circuit. Not that I'm saying no better solutions are available, it's just I haven't found anything that strikes me as 'better'.


----------



## trains galore

The issue is that pulling such high levels of current is going to put substantial strain on them and generate lots of heat, and is only really feasible if you can find a way to fit a reasonable sized heatsink in somehow, which will be difficult.

Perhaps you could convert some of the motors to can/sealed types, although it depends on the design of the gearbox and pick ups.

I was able to fit a small motor from an old computer cd rom drive (the one that opens up the tray) in place of the thoroughly worn out pancake motor in my old fleishmann. Far better slow speed control, plenty of power and none of the ozone smell or smoke from the stuffed windings! :smilie_daumenpos:

They also draw practically nothing in terms of current and are generally very good quality because they need to work smoothly. Of course it takes a fair bit of work to do this and you generally can't without modifying the frame, motor holder and gearbox. You also need a small rotary tool to do it properly, and I can understand that most collectors would want to keep everything original. I just wanted mine to work again!


----------



## Shdwdrgn

Well this particular 0-4-0 is by no means a collector item. From what I've been told here, it's just a cheap Life-Like that's not even prototype to any particular loco. However for my purposes it is perfect... This is an old unit that has probably seen a number of years of wear, a number of years of collecting dust, and a motor that is far from ideal. Overall it borders on a worse-case scenario, so if I can control this loco smoothly and reliably, then I should be able to take on any others with little or no modifications to my circuit. I was counting on it to be difficult.

And speaking of difficult, I think I've discovered the culprit in my problems. After successfully getting it running again, I thought I would try switching back to the 7805 to see if that might still be an option. Apparently it isn't. I know the 7805 requires capacitors on both sides, but that's not enough. By the way it is acting, I think it blew out the L293D driver chips again. I have a new dc-dc converter on its way, nearly the same size as the 7805 itself, and I think I'm going to wait for that to arrive before I muck with the circuit any more.


----------



## gunrunnerjohn

What are you driving the 7805 from the DCC track voltage? I can't imagine why it wouldn't work, though I'd be using a switcher for the power levels you're talking about.


----------



## Shdwdrgn

Yes, from the track power, although it is just straight DC, not a DCC system. The power pack is putting out about 17VDC, which I run through the bridge rectifier made up of 1n4001 diodes. If I measure the voltage across both sides of the 7805 I see a slight drop on the 17v side (I think it measured about 16.8v), and I see a solid 5.0v on the other side. However when I try to apply power to the motor, the high side of the 7805 drops into the upper 7v range. The 7805 I am using now is rated for 1.5A, so there shouldn't e a problem with current draw, and the 5v side never dips so the arduino stays running.

So I dunno... maybe it's because I'm trying to draw power from both sides of the 7805 (I need the 17v to go through the L293D to drive the motor) and using the center pin as a common ground for each, which it should be because the output of the bridge is connected directly to pins 1 and 2 of the 7805. Or maybe the 7805 just doesn't like my capacitors. I'm using a 330uF/35v on the high side and a set of caps totaling 9900uF/10v on the 5v side.

It's annoying, but I'm running out of motor driver chips. Need to put in an order for some more, but in the meantime I know the circuit works with my existing dc-dc converter, and I have high hopes for the new smaller dc-dc- converter when it arrives, so I'll just wait for that.


----------



## gunrunnerjohn

In order to reach anything close to 1.5A on the 7805, you need a honkin' heatsink! You are trying to drop 17V to 5V with a linear regulator, that's 12 watts power dissipation in that little package! In order to even approach that, you need a really significant heatsink. A switching power supply is the only way to go at these power levels if size is a consideration.


----------



## Shdwdrgn

I agree that I *would* need a heatsink, if the 7805 were getting hot. It's running about room temp, so it is not pulling anywhere near that amount of juice. And that's the main reason I'd rather stick with the dc-dc converter, because they don't generate waste heat from the voltage conversion, which is critical in a tight space.


----------



## gunrunnerjohn

The 7805 will get pretty warm pulling a couple hundred milliamps when you're dropping 12V. If you're getting excessive voltage on the output of the 7805 and it's not getting hot, something has to be wired wrong. I've been using three-terminal regulators for well over 30 years, they simply don't do that if something's not amiss in the circuit.

If the LM7805 isn't getting hot, it's the smallest part that is going to do the job, why are you changing?


----------



## Shdwdrgn

You read me wrong... I'm not getting excessive voltage, the 5v output is staying rock solid. I'm getting a large DROP on the input side... the original 17v is dropping down to 7v when the motor is engaged. I'm sure there's some crazy reason for it, and it was fun to play with for a bit, but it's just not worth pursuing since the 7805 is such a heat factory anyway.


----------



## gunrunnerjohn

That makes equally little sense to me. The only reason I can see for that is the input power source doesn't have the current capability being demanded by the load. This has nothing to do with the 7805 itself. The switcher would help, as it will be more efficient at power conversion, but it sounds like the 17V is a pretty weak power source.


----------



## Shdwdrgn

I'm using the same power supply on the track for each test circuit, and it certainly has enough power to drive the loco and electronics. If I dared let it run at full speed I think my little 0-4-0 would fly off the track, so there seems to be plenty of juice.


----------



## gunrunnerjohn

What can I say, there's no way a working 7805 exhibits what you say is happening. I'd have to see it to determine what's going on, but clearly something can't be as stated. If there's "plenty of power", something would have to be getting hot to drop all that voltage! I guess it's hard to quantify "plenty of power", what does that really mean?


----------



## Shdwdrgn

Jump back to post #29 and you can see how I have it wired, with the addition of a 330uF across pins 1 and 2 on the input side of the 7805. Yeah I don't get it, I've used 7812s before with no problem, I'm just not sure what's wrong. I just know that when I try to use it here, something pops inside the L293D, and it heats up immediately from the 17v power being fed to it, regardless of if the motor is actually supposed to be running.

I'll have to check the power supply tonight to see the exact rating, but in this case "plenty of power" simply means it has enough juice to drive the motor much faster than the loco should be run on an 18"r circle, so unless the 7805 is sinking a significant percentage of an amp by itself, there should be enough power to continue running the motor, and regardless it should NOT be blowing the driver chips.


----------



## trains galore

If the voltage straight from the transformer is dropping that much under load, then I agree it sounds like the power pack is not capable of delivering enough current, which is why it drops down so much.

Only other possibility is something isn't wired up right or there is a short somewhere. 

If you have another supply capable of delivering at least a few amps try it and see what happens, as sometimes the ''train set'' controllers struggle to power much more than 1 or two small trains, I know mine certainly does! 

Although given that the driver chips keep dying, it sounds like something else is causing this. If you haven't already tried it add in some filter caps across the output on the regulator circuit, these help to stop spikes which may be ruining the chip.

The 7805 usually gets quite warm especially when reducing that much power (17-5) so maybe try another if you have a spare?

I doubt this is significant but are there any ceramic capacitors across the motor? I often see these which I think are meant to supposedly stop surges and interference caused when the motor stops/starts. It might be something to try but again I'm not sure if it would make any difference. I have a can motor right here that has them, they look like this:


----------



## Shdwdrgn

The 7805 has 330uF across the input side and about 9900uF across the output (5v) side. The datasheet requires a capacitor across both side to properly work. I have tried two different 7805s and burned through four L293D chips so far (and just ordered a new bag of them this morning). As mentioned, the 7805 does not even get warm, so there is no significant current draw through it.

My motor does not have the capacitors, but you are right about their purpose. However the L293D has flyback diodes built in (if your motor has time to spin down, it will act as a generator and try to pump juice back into your circuit). Larger motors can cause enough ripple in the voltage supply to affect the arduino and cause it to restart, thus requiring capacitors across the motor or the L293D driver, however I have not had any trouble at all with the small motor in my loco. I do have the large bank of 9900uF capacitors to smooth the input voltage, but that is only because the wheels of the 0-4-0 make for a *very* noisy source.

So I checked my power pack, and was surprised... I think this thing must be from an N-scale layout because it only supplies 7VA at 17VDC -- not quite even half an amp, which really begs the question of how I was able to measure a draw of over 1amp from the loco motor, but it also indicates that there is a lot less current in the circuit than I originally believed. So how is it even possible that this could be blowing the L293D chip, which is wired to handle a full amp of current? Or for that matter, my doubled-up chips which should have been able to sink up to 2 amps?

Ah well, looks like the new dc-dc regulators should be here by late this week or early next week, and I can see if they work as reliably as the much larger one I'm using now. Also have a code-70 turnout and an 0-6-0 arriving on Friday, plus a steady stream of other components from China to play with.


----------



## gunrunnerjohn

Given the fact that the 7805 wasn't even getting warm, I don't see how it was passing much current at all. I can't imagine how replacing it with a DC-DC regulator with no other changes is going to fix things.


----------



## Shdwdrgn

John - except that it DOES. I have a dc-dc regulator I started out with (except the board is too large to fit inside my tender), and everything works perfectly fine with that board. No problems running the loco up to 15 minutes at a time, the L293D barely gets warm and nothing else feels warmer than room temp. The diodes are doing their job as a rectifier, I can throw the power supply in either direction and still get a proper +5V signal to the arduino. I also have a wifi board hooked up, so I can control the train speed and direction from a web interface. Everything works great when using the dc-dc regulator, but when I replace it with the 7805, the L293D dies (everything else continues to work, fortunately).

With the 7805 in place and the L293D motor power lead disconnected, I can measure 17v across pins 1-2 on the 7805, and 5v across pins 3-2 (1 is input, 2 is ground, 3 is output). If I had connected the 7805 incorrectly, I don't believe I would be seeing the correct voltages. But when I reconnect the 17v lead to the L293D, the chip immediately gets hot even without being enabled, and barely any juice makes it to the motor (probably only the 7v I had measured before). I don't even get the satisfaction of seeing the magic smoke, the chip just fries, and no longer works when I reconnect the dc-dc regulator.

For reference, this is the dc-dc regulator I'm currently using (currently outputting 4.99v): http://www.ebay.com/itm/5x-LM2596S-...ltage-Regulator-Arduino-UK-C505-/161419156290

And this is the new regulator I'm waiting on: http://www.ebay.com/itm/262130706775


----------



## gunrunnerjohn

It's obvious that something else in in play here, if the 7805 is passing the power for the circuit and it doesn't even get warm, it's hard to believe it's cooking motor drivers.

I'll refrain from further discussion since it's clear that I don't have the full picture.


----------



## gregc

have you tried powering up the circuit without the L293D

and if that doesn't short, adding the L293D without the motor and with the control inputs in a known safe state,

and if that doesn't short, with the control input connected to the controller

and if that doesn't short, adding the motor

or some simpler sequence to help identify the part of the circuit loading the supply


----------



## fcwilt

Post your schematic. The 7805 may be going into oscillation.


----------



## Shdwdrgn

gregc: Everything works fine until I connect the 17v lead to to motor supply pin on the L293D. The start-up sequence on the arduino pushes the L293D to disable the motor (and that seems to be the natural state of the components anyway as there is no jump in the motor before the arduino gets a change to initialize). 

fcwilt: schematic was posted in post #29 and just mentioned again yesterday in #73. Replace the 7805 with a dc-dc regulator that has a common ground, an input and an output line, and you've got the circuit that does work.

Seriously though folks... I really don't care about getting the 7805 to work! It was an interim test while waiting on other components to arrive, I never expected it to be permanent. The 78xx series is great for certain circumstances, but runs way too hot for this purpose. I'll wait a few more days for the new regulator to arrive and see how it fares.


----------



## Shdwdrgn

The new regulators finally arrived today. I ordered four of them, and went through all four with no ability to set or maintain the proper voltage. They would adjust from 0-2v, then jump into the 8v range, and if I changed the setting on the power pack, the output voltage would also change. I was getting pretty frustrated when I finally though of something -- I soldered an electrolytic cap across the input legs, and boom, precise regulated voltage output! Apparently the capacitor already on the board isn't doing squat. I'll have to play around to see if I can get it to work with a smaller capacitor, but for now the circuit is working properly, and my little loco is running around the track again.

Once I get the capacitor issue sorted out, I'll start tearing apart and rewiring the whole circuit to make it more compact to fit inside the coal tender. It's quite a rats nest now.


----------



## gunrunnerjohn

When you increase the load on those switchers, you need a lot of bulk capacitance on the input side. Some of the boards don't have any bulk capacitance at all, and the ones that do are only good for a couple hundred MA before you need more filtering.


----------



## Shdwdrgn

Unfortunately I didn't have any load at all on them while testing. I connected them directly to the track through the diode bridge, and hooked up my voltmeter to the output side of the board. This model is adjustable, so I needed to dial in the output voltage to about 5v before hooking it up to my arduino. Even worse, I would get it set for a particular voltage, pull it off the track and reconnect it, and would get a completely different output the next time. I mean, I know the output from an old bachmann transformer isn't going to be the cleanest source of power, but I would still expect the regulator to at least be consistent every time I apply power!

At least the addition of a cap is an easy fix, I just need to find one that has a good capacity with a small physical size. I'll probably do some testing on the circuit tonight, run the train for a bit to make sure nothing gets hot, and if it all looks good then I can start replacing the bulky wires some some smaller ones and figure out how to arrange the components inside the tender. Oh, also I'm back to a single L293D motor driver, since it appears the motor doesn't actually pull much juice at all.


----------



## gunrunnerjohn

Since the motor doesn't draw that much power, where is all the power going?


----------



## Shdwdrgn

When I was using the 7805, that was the big mystery. I'll try to get a new reading tonight with the loco and arduino running, but I'm betting it will be less than 500mA.


----------



## Shdwdrgn

All right, got a few runs around the track (having bad derail problems with all the electronics hanging over the sides). It looks like at full throttle the motor is pulling about 400mA, however it did peak at 700 at one point. Not sure if that was an actual surge in the motor or just my old meter being slow, however the driver chip is not getting very warm while running so I would tend to think the lower reading is more accurate. Running at 1/4 to 1/2 throttle I'm seeing a consistent 200mA, so that also follows.

So the dc-dc regulator and the driver chip are well over-rated to supply this old motor, I don't think I'll have any problem with running them for long periods.

I got a better read on a fairly new Bachmann 0-6-0 that is still straight DC. Near the power leads it pulled 360mA, and on the opposite side of the loop it pulled 600mA... Still well within tolerances, but makes a strong statement about the poor conductivity through standard rail joiners.


----------

