# Has anyone tried using laser for block signaling?



## Shdwdrgn (Dec 23, 2014)

I'm starting to look into ideas for block detection on my test track. I don't have any gaps cut to do current-detection so I wanted to look at optical options. Of course the easiest method is with IR LEDs, however there seems to be a lot of trouble with these due to interference with ambient light, especially if you are in a location where sunlight may be involved.

While digging around I found that you can buy laser heads really cheap these days. For a little over a dollar, I can get five heads that take a 5V supply and put out a 650nm dot. There are also detectors available that specifically pick up on the 650nm light. It also seems like using a shroud around the receiver would allow me to filter out ambient light and only pick up the pinpoint from the laser.

So has anyone tried this for model railroading? Any 'gotchas' that I might be missing? The only issue I can see if the physical size, as the laser head is 6x10mm, however a hole through the plywood and an angled mirror could create a sensor with a minimal surface area (much smaller than the LEDs).


----------



## gunrunnerjohn (Nov 10, 2010)

If you use modulated IR beams with intelligent detection, any issues with incident light is history.


----------



## wvgca (Jan 21, 2013)

modulated IR is the way to go, no problems with ambient ... 38k through 56k seem,s to work fine


----------



## Shdwdrgn (Dec 23, 2014)

Hmm so how does that work? Is there a filter built into the receivers that only triggers on the 38k signal, or do they just use a regular IR pair with an external circuit to send and receive the 38k signal?


----------



## gregc (Apr 25, 2015)

yes, the receiver has a filter, as well as an automatic gain control to manage the sensitivity to background light.

i looked at a product, i think from Iowa Scaled engineering where they simply turned off the emitters to help determine if the non-modulated detectors were sensing the emitter or background light. 

The other recommendation was to use shrink wrap to make the aperture on the sensor as tight as possible.


----------



## wvgca (Jan 21, 2013)

glad someone else answered, i didn't know ......
if it matters, i have no sgnalling or occupancy ..


----------



## Shdwdrgn (Dec 23, 2014)

Hmm ok I might have to play with that idea. I was thinking on an arduino-style board if you hooked up the LED sensors to ADC inputs then you could periodically turn off the IR LEDs, check ambient light at each sensor, and use that as a baseline for sensing the signal from the transmitter LEDs. Of course that's going to require a LOT of ADC ports.


----------



## gregc (Apr 25, 2015)

what's the purpose of using ADC ports


----------



## Shdwdrgn (Dec 23, 2014)

This would be with using standard IR LEDs instead of the 38K style. Instead of having a fixed frequency you could change it as needed. I read somewhere that some fluorescent bulbs can flicker at 36Khz and cause interference, and you never know what tomorrow's technology might introduce. But this is all just playing with ideas for now, I just want to see what all I can do and may use different devices for different locations.


----------



## gunrunnerjohn (Nov 10, 2010)

You're making this way to complicated! How about a $1.40 part that will sense 38khz modulated signals and give you a digital output. That way you can just generate the 38khz with a simple timer output and have reliable sensing.

Vishay IR Receiver Module for Light Barrier Systems

This is one of many similar such products, just the one I found on Digikey first.


----------



## wvgca (Jan 21, 2013)

you can get center frequencies between 30 khz and 57 khz, if it makes any difference with rejection bands


most of the recievers are a buck or so, makes a cheaper project ...
a timer or a modulated signal can act as the source, emitters are cheap alsp


----------



## gregc (Apr 25, 2015)

you just need a clock (555) at the receiver freq to drive the emitter(s)


----------



## Shdwdrgn (Dec 23, 2014)

I actually have some 4838 receivers on order, but I'm still trying to figure out the transmitter portion. Digging through the 38khz transmitters I'm seeing on ebay, a lot of them appear to be nothing more than a plain IR LED. I've seen a few 555 circuits to put out the 38Khz signal, but I'm kind of surprised there aren't any LEDs with the circuit built into them. Are there any such units that I'm missing, or is the 555 circuit the easiest way to make this work?


----------



## wvgca (Jan 21, 2013)

the are a few circuits that have led built in, but by far the most common is a plain IR led with timer driving it ...and easy too !


----------



## gregc (Apr 25, 2015)

since you need a device to generate the data packet, it shouldn't be difficult for that same device to generate each bit with a 38 kHz pulse train. Why use a more expensive IR LED?


----------



## gunrunnerjohn (Nov 10, 2010)

What happens after you detect the signal has tripped? If you're planning on any intelligence like an Arduino to process the signal, it can easily generate the modulated LED signal. You'll likely want things like delays when a train leaves the block, processing to drive crossbuck signals, etc. Why build multiple circuits when one Arduino will serve multiple signals?


----------



## Shdwdrgn (Dec 23, 2014)

I have some code for an arduino S88 sensor with 16 ports, but unfortunately all the other I/O pins on the arduino are taken up by the few lines needed for the S88 bus, so there are no free pins left over to generate the signal. However 555 timers are dirt-cheap and one chip could probably run all 16 of the IR LEDs for each block. I have a bunch of parts on order from China, so it'll be January before I can start playing around with it, but the new arduinos should be here before that and I can at least get one set up. I also need to get a frame built under my 4x4 test loop and mount some servos on the turnouts.

One question about the light sensors... has anyone seen a method of mounting them *under* the plywood? I was thinking maybe I could aim the IR beam through a pinhole, hit a 45-degree mirror to direct it across the tracks, then another mirror to bring the beam back down through a second pinhole to the 38Khz sensor. The mirrors could be a lot smaller than the LEDs, and hopefully easier to hide, but I'm not quite sure what I would use as a mirror at that size. Maybe a piece of aluminum foil would be good enough?


----------



## gunrunnerjohn (Nov 10, 2010)

One 555 with perhaps some extra drivers would run a bunch of LED's. 

I don't see anything wrong with mirrors, but the detector and the IR emitter are really small, so I'm not sure how much more compact it would be, and it would certainly add complication. The sensor is about 1/4" across, a simple signpost or similar would be enough to enclose it.


----------



## wvgca (Jan 21, 2013)

why not run just up and down ?? instead of a modulated signal indicating an abscence of rolling stock, the signal indicates a prescence ??


----------



## Shdwdrgn (Dec 23, 2014)

I might try running a pair vertically, but really that's going to depend on the reflectivity of the bottom of the cars. I've been weathering my cars with flat colors, however there is still the truck screw that should generate a brief flash, or maybe I can just polish up the bottom of the trucks to give a larger surface. And actually if memory serves, this method would work better anyway... The arduino S88 code expects an active-low signal and these sensors are also active-low. Of course I could always change the code to active-high if I need to, just have to wait and see what works.


----------



## wvgca (Jan 21, 2013)

here's a simple emitter / detector combo off of ebay ...for about 50 cents each
this thread was also done on mrr forum ..
here's a link to it http://cs.trains.com/mrr/f/88/t/273355.aspx

just needs shrink tube to localize the beams ....


View attachment 476586


----------



## gunrunnerjohn (Nov 10, 2010)

That one is not modulated, so it will pick up stray light and trigger.


----------



## wvgca (Jan 21, 2013)

gunrunnerjohn said:


> That one is not modulated, so it will pick up stray light and trigger.



that's primarily the reason for the shielding ... the OP expressed a desire for non modulated, turning the arduino on and off to allow for ambient light ..


just a different way to skin a cat, lol


----------



## gunrunnerjohn (Nov 10, 2010)

I'd go for reliability, but I'll stay tuned to see what shakes out. FWIW, I have a couple of those boards, but I wasn't all that impressed by their performance. Facing up to the bottom of the car would probably be worse as there's likely lights up there. When the train leaves, you see light and trigger, probably not the intended operation.


----------



## Shdwdrgn (Dec 23, 2014)

Actually I'm not opposed to modulated products. My original thoughts were to use an arduino to turn the LED or laser on and off at intervals and watch for matching triggers on the receiver as a method of eliminating false triggers, which is essentially what the modulated items are already doing without a computer program.

I wrote up a web page to play with methods of signaling occupied blocks based off of location sensors. That can be seen here: http://sourpuss.net/projects/trains/computer/testtrack/ (only tested in firefox, so no guarantees how well it works)
Each sensor resets a 5-second timer because I don't expect a sensor to be constantly tripped while a train is passing. The setup seems to be somewhat reasonable if you click sensors in sequence around the loop, each block progresses from red to yellow and back to clear, but I'm not quite certain if this simple setup would provide reliable operations. Something about it is nagging at me, I'm just not sure what exactly. Any thoughts? One thing I know for sure, if a train stops on the tracks in a spot where the sensors aren't tripped, then that block might be cleared while the train is still there, so I would need to add more logic to this.


----------



## gunrunnerjohn (Nov 10, 2010)

The good part about simply feeding the sensors into a uP based board is you can tune the behavior if your initial assumptions don't pan out. 

Things to consider is direction of travel and multiple tracks...


----------



## Shdwdrgn (Dec 23, 2014)

Well the code page uses an array to hold what sensors are next to what other sensors, and that's used to define the blocks. So if sensor 4 gets tripped then it assumes blocks between 3-4 and 4-5 are occupied. Multiple tracks shouldn't matter because the definitions of the blocks include the interconnections between tracks (I think). As for train direction, I could possibly create some logic to determine that but I'm not really sure that is needed?

Regarding trains that stop, an idea I'm playing through my head now makes use of the array above... basically mark a block as red when the sensor gets tripped, but don't allow it to drop back to yellow/clear until one of the sensors on either side of it gets tripped. That way I think a block would stay permanently red even if the train stops until there is some indication that the train is moving again. Ugh, having a lot of trouble organizing my thoughts into something I can coherently express here, but I'll try to incorporate it into the web page demo.


----------



## DennyM (Jan 3, 2016)

Interesting topic, but above my pay grade.


----------



## Shdwdrgn (Dec 23, 2014)

Got the code updated for that idea, and it actually seems to work really nicely now. A train can stop between sensors, back up, go forward again, and the red/yellow indicators appear to correctly follow the progress.

So now the only thing lacking is to maintain yellow indicators beside the red ones, without affecting the speed of the train that is actually within those blocks. That's gonna be a tough one, I think.


----------



## wvgca (Jan 21, 2013)

the web page simulator seems to work rather well ...
i -assume- arduino for this ??


----------



## gunrunnerjohn (Nov 10, 2010)

Web Simulator Page?


----------



## Shdwdrgn (Dec 23, 2014)

It could be arduino, it could be raspberry pi... I'm not really set on any of it yet, but ideally the code would be simple enough to run on an arduino with little effort.

There's still a number of problems with the code, though, mostly when you have multiple trains working in adjacent blocks. I think what I'm stuck on right now is the problem with short trains (like just the loco) which can disappear between the sensors. Consider if a loco trips a sensor, so I mark that sensor as active and the blocks on either side are set to red. OK so if the loco then trips one of the adjacent sensors, I can assume the loco has moved and clear the status of the previous sensor (which is basically what the web page is doing now).

Now... what if I have a longer train that trips multiple sensors as it passes? For example, if the train covers sensors 3 and 4. As the cars pass, each sensor will blink on and off. When 4 gets activated, 3 would be set to yellow, but then another cars passes on 3 and now 4 gets set to yellow. If I set a timer on a red section (allowing it to stay red for a few seconds before dropping to yellow) and the train stops with none of the sensors active, then after a few seconds the block would be cleared even though there is still a train sitting there. And the problem gets even worse with longer trains spanning more sensors.

Another thought was to automatically join blocks between two active sensors... so if a train spans three blocks but the center sensor isn't currently active, the code would just assume there is something between the two active sensors and mark the middle one as red. However what if you have two trains following closely together, with one following slowly in the yellow zones behind the lead train? There would still only be one inactive sensor between the two trains, and this code would mark it as occupied, thus stopping the train in the rear.

So many scenarios, so many ways to accidentally block a train which should be allowed to proceed (although I suppose that's better than allowing a train which should have been stopped). I think I'm going to have to take the complexity up another level on the code and keep two separate maps -- one marking where I *think* trains are currently at, and then generate a separate map of the red/yellow blocks. I dunno, this could get real ugly real fast, but I'll see how it goes.


----------



## gunrunnerjohn (Nov 10, 2010)

You'll drive yourself crazy if you try to cover every possible scenario.  I'd consider getting a basic structure of the code down with flexibility to add other options and then expand as the need arises.


----------



## wvgca (Jan 21, 2013)

gunrunnerjohn said:


> Web Simulator Page?



there is a rough web based code page at 

http://sourpuss.net/projects/trains/computer/testtrack/
easy accessible by -most- web browsers


----------



## gunrunnerjohn (Nov 10, 2010)

I'm supremely confused as to what it's supposed to illustrate!


----------



## wvgca (Jan 21, 2013)

it's just a simple code page, easily portable to an arduino or raspberry pi, to give sense to the outputs of the detectors ...
when you right click on a detector location, [numbered , to turn it active] it turns surrounding block red [occupied], and after a while to yellow [slow down], the some go clear, except the one  occupied by the train [ standing or moving] ..


----------



## Shdwdrgn (Dec 23, 2014)

LEFT click, not right 

But yeah, the idea is that each button represents one of the IR sensors. As a train passes that sensor may be flicked on and off, so the first step was to include a timer so the sensor didn't go dark immediately. If you click on the sensors sequentially around the loop, the trailing locations will go to yellow and then clear, and that much works smoothly for the assumption of a single short train. As usual, I'm not satisfied with that, and think I can do better, but I've been having sleep issues this week and my head is pretty fuzzy. I'll get it figured out, I just need to break down the possibilities until I figure out a method that I'm satisfied with.


----------



## Shdwdrgn (Dec 23, 2014)

Well I have an update on the test page, same link as before: http://sourpuss.net/projects/trains/computer/testtrack/

Still pretty simple code, but this one maintains a minimal sense of which direction the train is going and sets yellow blocks accordingly. It also responds to a train reversing direction. However I need to figure out a way to test this code with a longer train that might trip two sensors at once, I think that might confuse the code as to which direction the train is moving. Ah well, small steps...


----------



## crusader27529 (Apr 3, 2016)

*IR sensor detection*

With only one sensor at each block boundary, you cannot absolutely determine the direction of the train.

I'm in the final stages of testing a detector system that uses dual IR detectors at each block boundary, and can then determine train direction. Knowing direction, all that's needed is a simple counter to determine if the block is occupied or not. The count increments and decriments for each block based on direction. The system counts the wheels as they pass the detectors. If the count is zero, the block isn't occupied, otherwise it's occupied. Yes, it works with a train crossing both block boundaries at the same time (if the train is longer that the block), or multiple trains entering or leaving a block at the same time. All it does is determine if a block is occupied or not. What you do with that indication is up to you.

Actual usage of the occupied indications of each block is more complex, and done externally to the detection system. The system is DIY and based on the Arduino platform, and expected costs to make your own is $10 per block. There's a second version of the detection system that allows up to 2 protected turnouts per block (as opposed to unprotected industry type sidings), and that would cost about $15 per block. Both types interact with each other seamlessly.

The system will be offered on a web page as a bare PCB or completely assembled and tested without the socketed Arduino module included. I only expect to cover my time for the assembled PCBs and shipping. Otherwise, the sale prices will be my cost plus about 10% to cover overhead.

BTW, since it's optically detected, it doesn't require any rolling stock modifications, and is independent of what it any voltage is applied to the rails. Stay tuned......


----------



## gregc (Apr 25, 2015)

crusader27529 said:


> I'm in the final stages of testing a detector system that uses dual IR detectors at each block boundary, and can then determine train direction. Knowing direction, all that's needed is a simple counter to determine if the block is occupied or not. The count increments and decriments for each block based on direction.


i developed a signal system using dual optical detectors at block boundaries. I kept track of the direction of travel and which detector was active last to determine if a train is entering or exiting a block.

but i believe a simpler transformer detector will be economical and require less work to add to the layout along with turnout position monitoring.

precision position detection is, of course, more complicated and i'm interested is hearing what modelers develop.


----------



## crusader27529 (Apr 3, 2016)

I'd guess that you use the optical detectors to determine direction, and the current detection for block occupancy. To be 100% accurate, you'd need to make every piece of rolling stock detectable......this doesn't require any of that. One thing I don't understand about your setup is if you can detect a train in a block, why do you need to know its direction? Direction is superflous to detection in a block.

I keep a count of how many wheels enter or leave a block, either from East or West and the turnout directions (North and South???) with the same logic. The system receives count up or count down indications from other detectors that are adjacent to it, and adjusts the count accordingly. The turnout detection is independant of a turnout position, and assumes that if a wheel crossed the block boundary from any source, it is valid and accepts the count up or down. There is simplistic signal logic implemented for local signals that would be red if the block was occupied or the turnout was thrown divergent for a specific route, but it only really works if one turnout is used, because the actual configuration of the track involved wouldn't be known by the detectors. Since the code is open source, if a user wishes to control local signals with multiple turnouts, they can do what they wish. The code for the counter part is relatively simple, and not timing sensitive. The detector code is more complex and has 4 state machines running concurrently to monitor the track detectors, and I don't reccomend making changes, but there's nothing preventing it.

The code is NOT hobby level code, and actually has 4 Real-Time Tasks running on the Arduino (NANO or MEGA) using FreeRTOS. The design can switch between tasks very quickly. Originally, the system used an Arduino for each block boundary and a third for the counting part of the code. It was overkill, but trying to combine multiple state machines into one program is a monumentally difficult problem. The RTOS allowed me to partition the Arduino into segments that act more-or-less like individual modules. The code changes were minimal, once I figured out how to switch between tasks fast.

The system is completely functional without the 'local' signaling, so it's absolutely functional as designed. The system just connects from one detector to adjacent detectors with cheap CAT5 network cabling. The optical detection is connected to the track with Fiber Optical cable that can be mounted adjacent to the rails just above the top of the rails. 3d printer version of any mounts for the FO cables will be included.


----------



## gregc (Apr 25, 2015)

crusader27529 said:


> One thing I don't understand about your setup is if you can detect a train in a block, why do you need to know its direction? Direction is superflous to detection in a block.


when a train is crossing a boundary, it obviously occupies both blocks. it may be transiting between blocks, but it may also reverse direction after crossing the block <before completely crossing the boundary>.



crusader27529 said:


> The code is NOT hobby level code, and actually has 4 Real-Time Tasks running on the Arduino (NANO or MEGA) using FreeRTOS.


having worked on several embedded real-time applications w/o the need for an RTOS, it's hard for me to imagine an application running on an arduino needing one.



crusader27529 said:


> The system is completely functional without the 'local' signaling, so it's absolutely functional as designed.


??



crusader27529 said:


> The system just connects from one detector to adjacent detectors with cheap CAT5 network cabling.


i used a couple arduinos connected via RS-485. this allowed a PC to monitor status to provide a graphical display.


----------



## Shdwdrgn (Dec 23, 2014)

I had a moment of panic this week... was looking over my ebay orders and there was no sign of the 38k receivers!!! Oops, turned out I ordered those from aliexpress. *whew* I also found a sale on them while looking around, $1.24/5, so I ordered 20 more. The lasers came in yesterday, so hopefully that means the other parts will start arriving soon.

I've been thinking about doubling up the IR detectors to determine direction, as mentioned above. I'll definitely have to play with that. There are certain places like the ends of spurs where a single detector would be all I need, but everywhere else having the dual sensors to determine direction would be a lot easier than trying to calculate it from software.


----------



## wvgca (Jan 21, 2013)

glad to see the parts are slowly showing up ...
xmas is the absolute worst time to expect quick shipment, lol


----------



## crusader27529 (Apr 3, 2016)

*Using a RTOS with an Arduino*

To gregc:

Each of the 4 state machines that are running have 9 states each, so trying to combine that into one really big state machine would require either 9 factorial (I really don't remember the terminology, as it was a long time ago when I worked with probability theory) for 4 numbers, or 9 to the fourth power number of states, but I'm not sure which. 9 factorial for 4 numbers at a time is 3,024 and nine to the fourth is 6,561. Even if my math is off by a factor of 10, the number of states to be accounted for would make the code unworkable.

Without going into detail, it would require the 4 state machines to be part of another state machine that managed the other four. Assuming that it would fit into an Arduino NANO, trying to debug the code would be a nightmare.

Using the RTOS allowed me to essentially keep the code amazingly un-modified, so each task can be debugged individually. Initially, I was seriously concerned about timing because the FreeRTOS uses the watchdog timer for it's basic time management, so the smallest time slice for each task would be 15ms. So, to loop through all 3 tasks(only three tasks initially), it would take 45ms, and the required detection window couldn't be met.

Using the priority of each task, I worked out a way for the running task to change the priority of the next task so it would immediately start executing. That worked on paper, but the code complexity bothered me. I found a way to switch among tasks of the same priority that worked better, and the context switch was only 200us. So, going through the state machines in sequence would only have 600us overhead, which was more than fast enough.

Sorry for writing so much, but without you having an understanding of why the RTOS was chosen needed some detail. To complicate matters, I don't have an in-circuit-emulator, so all the debugging would have to be done with print statements or something similar. That's how I got the original code to work, and it was a PITA, and took a decent amount of time.

I'll go away now.....


----------



## gregc (Apr 25, 2015)

i feel discussions like this imply that certain things are very complicated and beyond the abilities of most models. They are not.

this reminds me of arguments at work -- "no other way". Eventually i had to re-write someone else's code because it was too simple and didn't meet requirements, non-maintainable or overly complicated when needing to be modified


the paired optical block detection code i wrote running on a single Arduino monitored multiple optical detectors to determine block occupancy in the adjacent blocks. Each pair had a state machine. I didn't need a real-time multi-tasking OS. (see below)




crusader27529 said:


> Using the priority of each task, I worked out a way for the running task to change the priority of the next task so it would immediately start executing.


sounds like you defeated the benefit of an OS by having one task determine the next task to run



crusader27529 said:


> I found a way to switch among tasks of the same priority that worked better, and the context switch was only 200us.
> 
> ... so the smallest time slice for each task would be 15ms.


doesn't sound very real-time. The first DSP application I worked on had a 125 usec cycle.



crusader27529 said:


> Each of the 4 state machines that are running have 9 states each, so trying to combine that into one really big state machine ...


of course you shouldn't combine everything into a single state machine. no need to.

state machines are often event driven. A windows application doesn't run, is suspended, until there is an event: mouse move, mouse click or keyboard input.

in your case I don't see why the Arduino loop() can't monitor the optical detectors pairs for changes and when a change is detected, update the state machine for that pair and do whatever action is required. should take < 200 usec

i implement state machines as two matrices indexed by state and event: one is the next state, the other is the action routine. transitioning from state to the next is simply a pair of table lookups. I've seen people go nuts trying to work with state machine implemented as nested case or if/else if statements.




crusader27529 said:


> To complicate matters, I don't have an in-circuit-emulator, so all the debugging would have to be done with print statements or something similar.


i often look at Arduino code in simulation on my laptop as a command line (cygwin) application.

I write stub functions for the Arduino functions (e.g. pinMode(), digitalWrite(), Serial.print()). My main() calls a function to read commands from a file. Those command might change pin states which are stored and returned when digitalRead() is invoked. loop() is typically invoked after each command is read.

i often look at code posted on forums in simulation to understand them better. I'm pretty sure i developed my paired-optical detector code in simulation before testing on the layout.




crusader27529 said:


> I'll go away now.....


i found the time values you posted for the RTOS informative.

i'm still looking for a application that stresses the resources of an arduino. Hearing about one using an RTOS was interesting.

others may find the discussion interesting


----------



## wvgca (Jan 21, 2013)

gregc said:


> i
> others may find the discussion interesting



yes, definitely interesting ..


----------



## gunrunnerjohn (Nov 10, 2010)

FWIW, for many years I developed aerospace applications. I did mission critical stuff like air data computers, primary flight instruments, and fuel management systems for commercial and military aircraft. None of my code required an RTOS to function properly, even though there are frequently many balls in the air. Typically, the cycle time was required to be in the 10 to 25 millisecond range. All of these applications used a pretty classic embedded systems architecture, a main loop that simple runs forever, all the required processing is simply handled within the loop. Obviously, there are copious use of timers and interrupts to manage sub-tasks that are not required to have the real-time response of the main loop. BTW, last year someone pointed out to me that the architecture is called _Super Loop Architecture_. In all my time using it, I never heard that term, I never knew I was doing "Super" programming! 

I don't doubt that similar tasks can be done with an RTOS, but for all but the most complicated systems, that's normally overkill, at least IMO. Another point about the RTOS, when you're working on aerospace applications that have to be certified by the FAA, every line of code has to be certified, including the entire RTOS if you're using one. Also, the code has to be totally deterministic, that means that you have to verify that your main processing loop ALWAYS has sufficient time to complete all necessary processing. Introducing an RTOS into the picture greatly complicates this process.


----------



## gregc (Apr 25, 2015)

gunrunnerjohn said:


> All of these applications used a pretty classic embedded systems architecture, a main loop that simple runs forever, all the required processing is simply handled within the loop.


that's been my experience. As a single developer, i was able to do everything required within a single loop and some interrupts.

before windows, i was told a multi-tasking OS is a social management tool. Each developer worked on a particular task and that allowed some independence.

unix was developed to allow multiple users to use a single computer.

today, multi-tasking OSs allow our laptops to provide various services and run multiple applications at the same time. They allow the user to multi-task thru multiple windows.


----------



## crusader27529 (Apr 3, 2016)

Calling FreeRTOS on an Arduino class computer a real RTOS is wishful thinking. It has support for inter-task communications and multiple priority levels, but that's all. It's not a REAL RTOS. An RTOS can specifically schedule various tasks at specific times or frequencies, and this has none of that support.

The primary use for me is the isolation of tasks and the ability to do fast context switching between tasks. I wrote lots of system code that ran in continuous loops, where interrupts woke up various bits and pieces of HW to interrogate something and place the result in a 'mailbox' that the primary loop was looking at. Multiple HW interrupts and timer based interrupts were used to update the 'mailboxes' so the primary loop knew what was happening. Multiple systems were based on this technique, mostly internal to video games. State machines in the primary loop allowed debounce of switches and not waiting for a switch opening after a closure, but all this os 'old school'.

I any case, how I did what I did using the Arduino was a quick and proven way to manage not having to worry about stack related issues, at least. Using an envelope like FreeRTOS allowed me to concentrate on the primary code functionality. I know in other environments that my choices of how to implement the architecture of any particular system will vary, based an inumerable factors that neither you or I can determine until we actually implement the project. My decision this time will be different based on performance and PRICE issues in determining the HW I can use, and how that HW is supported by code.

So, without really knowing all the details and decisions I needed to allow for, you can't even come close to tell me if I did it wrong in your OPINION. Time constraints in producing the code and actual performance, plus available tools in the development process add decision points that obviously make every project unique. As long as the results meet price and performance goals, my solution is as good as any.


----------



## gregc (Apr 25, 2015)

crusader27529 said:


> So, without really knowing all the details and decisions I needed to allow for


i'd be interested in hearing what those details are.

how many detectors, how frequent the events are, how long it takes to service the state machine, what actions are performed, ...


----------



## gunrunnerjohn (Nov 10, 2010)

crusader27529 said:


> So, without really knowing all the details and decisions I needed to allow for, you can't even come close to tell me if I did it wrong in your OPINION. Time constraints in producing the code and actual performance, plus available tools in the development process add decision points that obviously make every project unique. As long as the results meet price and performance goals, my solution is as good as any.


Did I miss something?  I don't recall saying you did something wrong, just that I wouldn't do it that way. I simply stated I never felt the need for an RTOS for any of the embedded programming I did, so I personally consider it overkill. The only person you have to satisfy with your process is you.


----------



## crusader27529 (Apr 3, 2016)

gunrunnerjohn:
No, you didn't miss anything. I was sort-of responding to gregc and his apparent criticism of my techniques for this project. You just got caught up in my response.

gregc:
I'll try to give yoiu some ideas of what I had to contend with and the timings that resulted. Hopefully my math is correct.

The main design goal of this project is absolutely reliable detection without having to modify any rolling stock. Athough current sensing works more-or-less, but to absolutely detect everything, every piece of rolling stock requires some modification, and let's be realistic, that just doesn't happen. And it won't work on dead-rail systems, which appear to have some future.

Basically there are 4 sensors, 2 for each block entry/exit. There's a state machine for each direction on each of the block ends for a total of four state machines. Worst case is that I have ALL the state machines in some part of their sequence, but once the state machines at each end reach the state where it preliminarily determines a direction at the start of the cycle, then there are only 2 machines active. Worst case is that there is detection activity at both ends of the block at the same time, whether or not it's the same train transiting a short block or different trains at each end of a long block doesn't matter, but must be allowed for.

The sensors at each block boundary are located .1" apart in tandem at the railhead. In a perfect world with square wheels, detection would be for the entire .1", but with round wheels, that detection is somewhat less, by some small amount. I'll use the square wheel design for the timing.

The projected goal for the sensor project is to detect reliably at speeds up to 99 scale mph. The prototype that used individual Arduino NANOs for each detection could reliably detect above 200 scale mph, as measured with an onboard speedometer, so I know the logic/state machines are plenty fast enough for the purpose. Besides the actual sensing, the sensors communicate with the counter modules at BOTH sides of the block boundary. That communication is a positive, requiring an acknowledgement for all events. That adds some indeterminate time to the process because although the other modules are the same and operate quickly, there's no guarantee where in their state machine that they are at, and it can cause some delay.

99 mph is approximately 20 scale inches per second, and math says that with .1" spacing both sensors will both be covered for maximum is 5ms. So, with the worst case scenario of some activity on all 4 state machines, there's only 5ms available. That gives me enough time with some to spare. Using the RTOS as I'm doing, subtracts some the time available for worst case detection, but not much. Each context switch is accomplished in a measured 175us, so worst case overhead for the 3 tasks(2 detector tasks and one counter task) is 525us. I can live with that considering it RTOS allowed me to essentially re-use the code that I used in the individual Arduino modules with minimal changes. The beauty of the RTOS is that I can add functionality beyond what is needed now by simply adding another task if needed, with minimal overhead, instead of changing the core code. We all know about Murphy, and how just simple changes to working code in a time critical design can result in unintended results.

Lastly was cost of the HW, and Arduino modules are hard to beat. The initial design allowed for one turnout per block, which required communication with the counter module only, so I called this the North block boundary. That was a nice addition, and expanded the usage, but I soon realized that one turnout wasn't enough, so I added a second turnout, which I call the South block, also with just communications with the counter module. Remember, the counter module only communicates with a detector module. Putting this on a single Arduino required the use of a MEGA module only because of the number of pins needed. The modules I use are Arduino MEGA Pro, which are the MEGA equivalent to the NANO module. They are designed for use in projects as opposed to experimenting with, and are smaller, and I install simple headers on the PCB so they can be easily installed or replaced.

Now it seemed excessive to require a MEGA when no turnouts were needed for a block, considering the extra cost of the MEGA. Asian prices for the MEGA Pro is about $9 shipped, where the NANO is about $3. So I decided to see if the code could fit in the NANO, and it could, and run reliably. So, I designed another PCB for the NANO instead of the MEGA that's identical, except thet it doesn't have the connections for North and South blocks. So, you'd use MEGA where you needed one or two turnouts in a block, and the NANO where you didn't have any turnout in the block. Since they run the same code, including the RTOS and run at the same speed, they interact perfectly.

Besides the requirement to reliable detection, there was a price goal in mind. My prototype counldn't meet the goal of $10/block, because it required 3 Arduino NANO modules, plus the other pieces to make a complete system. Plus the sensors were mounted to across the tracks, which although they worked fine, didn't pass the protypical look of railroad equipment because they were difficult to hide. The new system has ALL the electrical components mounted on one PCB, with the sensors based on fiber optic strands that mount across one rail, and are small enough to hide easily. So, the NANO version of the detection system can be made for the target of $10 with some judicious shopping on EBAY. Did I forget to mention all the components are available on EBAY? Actually, it's cheaper to acquire the IR detectors from Mouser or Digi-Key, and take advantage of quantity pricing, which saves a bunch. Once you validate that this works as expected, and meets you needs, it's time to acquire parts, and even a small club would likely have 10 or more blocks that they would want detection protection, and large layouts would need more. The MEGA module would likely cost about $16 per module.

This entire project is DIY, and I'll be selling the PCBs and probably offer some assembly, but the system is OPEN SOURCE, both HW & SW.

Speaking of open source SW, the system has outputs for up to 4 simplistic signals if anyone wants to do something with that. The pins on the Arduino MEGA module only(I didn't have enough I/O on the NANO) are defined, but don't have any connection to the outside world, because I think that any real signaling on a layout would require much more logic that I could allow for considering all the possible variations in signaling.

That's all that I can think of at the moment, so if you want specific answers about something, just let me know, either in response to this posting or a private message.


----------



## gunrunnerjohn (Nov 10, 2010)

crusader27529 said:


> gunrunnerjohn:
> No, you didn't miss anything. I was sort-of responding to gregc and his apparent criticism of my techniques for this project. You just got caught up in my response.


That's good, I had to go back for a minute and see what I said to elicit such a response.  I've done projects with an RTOS, just not sure I'd do this one with it. However, there's no reason it won't do the job, and if you're comfortable in that environment, that's probably the way to go. After coding up a ton of stuff with the "Super Loop" (love that term), I'm just more at home working that way.


----------



## crusader27529 (Apr 3, 2016)

FYI, I was incorrect in my timing assessment concerning the context switch times using FreeRTOS.

My initial analysis showed that I looped back to the task toggling a LED every 175usec, and I incorrectly assumed that was the time for each task context switch, but in reality it was the time before I looped back to the task toggling the LED, executing all the other tasks, in sequence.

So, that 175usec was the context switch for 3 or 4 tasks to loop back to the test task. I currently am using 4 tasks for my project, but I'm somewhat sure that when I measured the time, that I had 3 tasks active, so the actual contect switch time is approximnately 60usec. If my timing was for 4 tasks, that would be 45usec. Taking worst case, I'll accept the 60usec time.

This makes the detection window even easier to meet. I'll be getting some PCBs made in a few weeks(hopefully), to do some verification. I've alredy verified that the FO cables can indeed detect transitions as expected.


----------



## gunrunnerjohn (Nov 10, 2010)

With any modern uP, it's pretty difficult to run up the score so you couldn't make a decent cycle time, so I'm sure that you should have no major difficulties even if there are more tasks added.


----------

