Skip to main content

HC-SR04 Ultrasonic Sensor

Train Detection Block Signals

I thought I share the use of this ultrasonic sensor, I was able to utilize the sensor in my outdoor dead rail layout as a train/block detection on my layout.

Since converting the Baldy & Palms Railroad to “dead rail” in early 2021, the track detection circuit on the upper loop has been functioning correctly about 80% of the time.  The reed switch circuit would get triggered by the magnets at one end of the block and not at the other end.  This made the circuit go out of sync.  I decided to try several other sensors with the Arduino to find a suitable solution. I tried the current sensor, voltage sensor, relay circuit, and the IR sensor, none of these performed reliably.  

E5AAA3D6-6672-4723-A343-8FA647551FB3CC6447FA-7E70-465F-A3A1-868B85D6BD7A67884DD9-A5F2-4578-9331-ACD003FE76B0I discovered the HC-SR04 ultrasonic sensor and decided to experiment with this sensor.  I also created a better Arduino code with the HC-SR04 sensor.  I adapted the HC-SR04 sensor to fit in a small signal shed to match and blend with the block signal.  The Arduino code is written so the HC-SR04 monitors motion from about 4 to 8 CM across the track. When a train is detected on one end of the block, the signal will turn red, and remain red until the train exits the other end of the block, at which the signal will reset to a clear green signal.  This can be used with two or three aspect signals.  The code just needs a few lines of code activated. The circuit has performed very well, so I plan to incorporate this circuit in other trains detection blocks on the layout. Check out the YT video for the Arduino code sketch and circuit design.   YT Video - HC-SR04 Block Signal

Hope this post helps other outdoor layouts having the same problem and eliminate the need to put magnets on locomotives and rolling stock.

Attachments

Images (3)
  • E5AAA3D6-6672-4723-A343-8FA647551FB3: Approaching upper loop
  • CC6447FA-7E70-465F-A3A1-868B85D6BD7A: Exit upper loop
  • 67884DD9-A5F2-4578-9331-ACD003FE76B0: HC-SR04 sensor
Videos (1)
trim.349B1F13-F9FE-4C7B-B3ED-5CC63BAD6F68
Last edited by sjbuff
Original Post

Replies sorted oldest to newest

@sjbuff posted:

HC-SR02 Ultrasonic Sensor

...

Maybe a typo; I think it's the HC-SR04 (not 02).  For 78 cents (including shipping) I just bought one just to see what it is!  It may not get here for a couple months but oh well!

hc-sr04

If you have a datasheet or something with more technical specs than the typical eBay Asia website provides please post it...

Or a bit more from Amazon with presumably faster delivery...

a bit more on Amazon

Attachments

Images (2)
  • hc-sr04
  • a bit more on Amazon
Last edited by stan2004
@SteveH posted:

Ron, this appears to be a great solution for block detection, especially for an outdoor layout. Thank you for sharing.

Maybe a dumb question as I assume you would have designed it this way... Do your hardware configuration and sketch provide for block occupancy signalling if a train runs in either direction?

I'm curious, would that require you to know the direction the train is running in....how does that work?

@A. Wells Can you please rephrase you question, I don't understand what you're asking.

If my question was unclear, here's another way to ask it.  Since the sensors merely detect a series of 8 transmitted 40kHz pulses reflected back to itself from the train passing in front of it, the sensor itself would be unaware of which direction a train is passing.  The sketch would need to be written in such a way as to turn on the signals when a train enters the detection zone from either end, and off again when it exits.  I don't presently have the knowledge to understand what the sketch does exactly, but this is something I'm considering learning more about.

@SteveH posted:

@A. Wells Can you please rephrase you question, I don't understand what you're asking.

If my question was unclear, here's another way to ask it.  Since the sensors merely detect a series of 8 transmitted 40kHz pulses reflected back to itself from the train passing in front of it, the sensor itself would be unaware of which direction a train is passing.  The sketch would need to be written in such a way as to turn on the signals when a train enters the detection zone from either end, and off again when it exits.  I don't presently have the knowledge to understand what the sketch does exactly, but this is something I'm considering learning more about.

Oh, gotcha!  Like with my crossing gate set-up which requires 4 magic areas.  Two to detect the train entering the outer area from either direction and two to detect when trains leave the gate area.  (I'm still waiting on a magic refill from Mouser.)

I'm assuming I can get away with not having to detect the direction of the train.  However, if I'm going to need to get an estimate of speed, I might as well to report direction.

Last edited by A. Wells

SteveH  and other interested: 

I added the Arduino sketch, which you may use and tweak to fit your design.  Let me do my best to explain how the sketch works with the ultrasonic sensor.  When Arduino is first powered up, the two HC-RS04's are initiated to get their bearing.  The sensors are now pinging outward to a distance of about 100 centimeters.   Same time the block signal is defaulted to a clear GREEN signal.  As the Arduino code runs the loop of code, the code is looking for changes in the distance sensing of both HC-SR04's.  I have written the code so the HC-SR04's are looking for changes between 4 and 8 centimeters. Any object detected outside the parameters is ignored. Once either side of the block (either HC-SR04) detects a object within the trigger parameters, the code will initiate the code for the signal to change a occupied RED signal. 

Now the train has entered into the occupied block section. The signal will now remain in a occupied RED state until the train exits the other end of the block. I wrote the Arduino code to only switch case to  the default clear GREEN signal when the train exits the opposite end of the block. Since I'm using two aspect signals, I needed to transition mode from RED to GREEN, so I added a flashing red sequence for a few seconds until returning to default clear GREEN status.

The train can come from either direction to occupy the block, but in order to clear the block the train needs to exit the opposite side of the block.  Instead of the flashing red sequence, you could add a YELLOW signal for a few seconds before returning to default clear signal.  (This code is in the sketch, but is not active.)

What's happening when the train is in the occupied block, and has pasted one of the HC-SR04 sensors.  The exit sensor is waiting for a object trigger to move to the next case of beginning the default clear signal sequence.  Until the exit sensor is triggered, the block state will remain occupied RED state.

I am also working on a circuit with the HC-SR04 for a grade crossing activation.  With pretty much the same code principals.  They're a bunch of things you can do with this circuit, tie the sensor to a station announcement for instance, or sawmill sounds when approaching a lumber mill siding.  All this is done through the Arduino and a sound board and is activates the animation when a train rolls by.

I hope this explains how I'm using the HC-SR04 to detect trains.  I found this to be good solution to my outdoor o scale layout.  I went with this method, because I did not want to rely on the track continuity to maintain the circuit state.  This way, once the senor is triggered, the state remains same until another trigger and a change of state.

Attachments

This is "other interested".  Do you have any issues with false leave detections  when the open areas between cars pass in front the sensors?  Have you considered using a comparator IC with low and high values (hysteresis) and pots to trigger a signal into the Arduino?  This would make it easier to adjust on the fly instead of having to recompile the code.

Other Interested

What amazes me (I watched your video) is how you methodically experimented with various technologies - optical, magnetic, electrical, and finally acoustic - to arrive at a solution.

My 78-cent free-shipping (!) acoustic module won't get here for months if at all but what I want to see if it's practical for the average OGR reader to apply this.  By that, I think most guys think of the 153IR ($45.99 MSRP) as the standard for occupancy detection when insulated-rail is not an option.  You simply position the 153IR next to the track, apply AC Accessory power, and hook the controlled accessory (signal, crossing gate, whatever) directly to some screw-terminals.  No soldering, no programming, no fuss, no muss!

Remember folks, OGR is a discussion forum and we're in the Electrical section.  So I may be talking to an audience of 1 (myself) but oh well!

In reviewing the datasheet, what's needed is a periodic pulse to trigger the module to send out an acoustic pulse.  This might occur, say, 10 times per second.  The module looks for an echo from the inaudible (ultrasonic) burst hitting a passing train in which case it generates an "echo detected" pulse.  The elapsed time (measured in a fraction of a second) from trigger to echo indicates how far the target is.  A building or other scenery structure on the other side of the track will generate an echo so the "trick" is to measure time to the echo and discriminate (ignore) reflections that come from distant objects (vs. a passing train).  All this indeed takes advantage of the "power" of an Arduino.

What I'm pondering is if it's practical and cost-effective to cobble together a circuit that embeds this 78-cent module into a, say, $5-10 DIY module that emulates a 153IR...without an Arduino.  While the Arduino and the like have been a godsend to the O-gauge community, it can be a daunting endeavor to the average OGR reader.  Likewise, there are many who find soldering or working at the component-level a show-stopper.  I get that.

Last edited by stan2004
@stan2004 posted:
What I'm pondering is if it's practical and cost-effective to cobble together a circuit that embeds this 78-cent module into a, say, $5-10 DIY module that emulates a 153IR...without an Arduino.  While the Arduino and the like have been a godsend to the O-gauge community, it can be a daunting endeavor to the average OGR reader.  Likewise, there are many who find soldering or working at the component-level a show-stopper.  I get that.

It's obviously possible, but I don't know if you'll hit that price target.

This statement in the data sheet is a bit confusing.

When tested objects, the range of area is not less than 0.5 square meters
and the plane requests as smooth as possible, otherwise ,it will affect the
results of measuring.

I hope that doesn't mean they expect that large an object to range on, we'll have to go to bigger engines!

Thanks all, remember my main issue was to get a sensor to function in the outdoor ambient light of sunshine and shadows throughout the day.  Also I am running dead rail, so there is zero track voltage as well.  I tried the 153IR, but did not get reliable results.  The HC-SR04 has been error free since I installed.  I am quite impressed.  I agree for most OGR reader and railroaders, the IR sensor, voltage and current sensors would probably work just fine indoors.   Many in the G scale layout use the reed switch and magnet circuit, but I found this to be not 100%.  I did use this method for awhile until I found this ultrasonic sensor.

I have been fiddling with the Arduino for awhile now, and YES the code and understanding of coding and circuit can be intimidating for many.  I've spend a lot of time learning the code and building circuits, which I enjoy.  Now to apply this to my layout is what I'm working to achieve.  Plans for other circuits are also in the works.

Attachments

Images (1)
  • HC-SR04_block_detection_circuit: Tinkercad circuit

For those who might be interested, here's avideo on the HC-SR04 from YouTube. It's 48 minutes long but fairly comprehensive. It shows how to use the Arduino with this device and provides code to program the sensor in raw form as well as how to program it with a library.

He concentrates somewhat on getting accurate readings for distance measurements including using a temperature and humidity sensor to calculate the speed of sound with more precision.

I realize that this amount of accuracy is not pertinent to this application, but you might imagine being able to differentiate between two trains on parallel tracks.

It’s all in the code, I’m pretty sure code can be written to sense different distance. My code looks for objects within 4 and 8cm. Adding code to sense a different area should be doable. Within the range of the sensor. This will be something I can experiment with.  The video from the Dronebot Workshop is very comprehensive and worth the watch for those seeking more information on this sensor.

...

This statement in the data sheet is a bit confusing.

When tested objects, the range of area is not less than 0.5 square meters
and the plane requests as smooth as possible, otherwise ,it will affect the
results of measuring.

Yup.  That's why I wanted to mess with one.  I'm thinking the 0.5 sq. meter "range of area" is suggesting you don't want interfering clutter that can create false reflections.  Or maybe it means you don't want a separate HC-SR04 within that range because of interference.  The smoothness might be implying the target should be a flat surface perpendicular to the acoustic burst for better reflection.

I see this as part-and-parcel of learning about this "technology."  That is, with the IR technology we've learned how ambient lighting (especially sunlight) can interfere with operation.  Likewise, the IR reflections are better when the passing train is white or lightly colored rather than black or dark.

Last edited by stan2004

@SteveH - This goes back to one of your early comments regarding detecting train direction and block occupation detection.  There is a scenario where you can make a block think it's empty (when it's actually not) by reversing the consist while it's over the "last" detector.  However, I think for most people this isn't necessary and just a matter of pedantics.  For a crossing gate though, it might be a necessity.

Anthony

Sure you can.  The block has signals on both ends, when either sensor is triggered, the blocks is turns RED.  Take it, in my scenario - trains roll through the block, there is no need to stop in the block and reverse back from the entering sensor.  Which if the train did reverse the train back out, the sensor would still remain RED, because the code is waiting for a trigger on the other end of the block.  Yeah a train could roll into the block from the other end, past the RED and trigger the CLEAR sequence.

But this scenario would not always play out, I'd lose my model railroading engineers certificate blowing by a RED signal. haha 😊

My next project is a crossing gate circuit, which has the same theory in mind, a trigger to active crossing gates when train approaches and another trigger when train exits the crossing gate area.  The Arduino code is where all the animation can be controlled.

@sjbuff posted:

Sure you can.  The block has signals on both ends, when either sensor is triggered, the blocks is turns RED.  Take it, in my scenario - trains roll through the block, there is no need to stop in the block and reverse back from the entering sensor.  Which if the train did reverse the train back out, the sensor would still remain RED, because the code is waiting for a trigger on the other end of the block.  Yeah a train could roll into the block from the other end, past the RED and trigger the CLEAR sequence.

But this scenario would not always play out, I'd lose my model railroading engineers certificate blowing by a RED signal. haha 😊

My next project is a crossing gate circuit, which has the same theory in mind, a trigger to active crossing gates when train approaches and another trigger when train exits the crossing gate area.  The Arduino code is where all the animation can be controlled.

I'm curious if you saw my topic on Crossing Gate Regulations from last week?  I want to try to make it as close to real life as possible.  I didn't want the gates to come down right when the train is on top of the crossing.  This wouldn't be good for my tractor trailers.

A. Wells. /No I did not, I’ll go check out your post. My thought is to have the sensor, say 3 feet away from crossing on both sides , and trigger lights and gates to the approaching train, and clear when other sensor detects the train has pasted. Returning gate up and stopping the flashing lights.  I also thought of placing a flashing amber light as the default state, then I know the circuit is working. I’ve seen European crossings with a slow flashing amber light when crossing is clear and moves to flashing red when a train is approaching.  I know not prototypical for US crossings, but it’s cool to see the crossing always active.

I received my 78 cent HC-SR04 and designed a circuit to make it work like the Lionel 153IR or MTH Scaletrax ITAD.

HC-SR04 proof of concept - january 2022

That is, you supply AC Accessory voltage.  You position the occupancy detector on the side of a track.  You hook up the controlled accessory to the relay outputs.  You set the sensitivity/range ... for example to detect a engine across a 2nd distant parallel track.  You set the time delay to keep relay on after train passes.

It works swimmingly and could be done for $5 in jelly-bean components for a well-stocked DIY'er.  My out-of-pocket was just the 78 cents for the sensor module.  I don't recommend you try this at home since it is a lot of component-level assembly and such.  I show the 153IR and ITAD by way of "size" comparison to show the circuit could fit in a trackside cabinet albeit there would be some work to custom-fabricate a housing maybe requiring a 3-D printer or whatever.

But if anyone is truly interested in how I did it, I can elaborate my observations and thinking.

This is a very interesting module which is very widely available and very widely used especially in hobbyist and robotics applications.  Just google HC-SR04 and you will be overwhelmed!

Thank you @sjbuff for introducing this technology to the forum!

Attachments

Images (1)
  • HC-SR04 proof of concept - january 2022
@stan2004 posted:

I received my 78 cent HC-SR04 and designed a circuit to make it work like the Lionel 153IR or MTH Scaletrax ITAD.

That is, you supply AC Accessory voltage.  You position the occupancy detector on the side of a track.  You hook up the controlled accessory to the relay outputs.  You set the sensitivity/range ... for example to detect a engine across a 2nd distant parallel track.  You set the time delay to keep relay on after train passes.

It works swimmingly and could be done for $5 in jelly-bean components for a well-stocked DIY'er.  My out-of-pocket was just the 78 cents for the sensor module.  I don't recommend you try this at home since it is a lot of component-level assembly and such.  I show the 153IR and ITAD by way of "size" comparison to show the circuit could fit in a trackside cabinet albeit there would be some work to custom-fabricate a housing maybe requiring a 3-D printer or whatever.

But if anyone is truly interested in how I did it, I can elaborate my observations and thinking.

This is a very interesting module which is very widely available and very widely used especially in hobbyist and robotics applications.  Just google HC-SR04 and you will be overwhelmed!

Thank you @sjbuff for introducing this technology to the forum!

Stan, can I get the schematic and BOM for this?  I'll create and post a PCB that will make assembly practical for a wider audience if they don't have to do a lot of wiring.

hc-sr04 proof of concept

Image should be expandable.

Here's the theory of operation.  Reviewing the HC-SR04 datasheet first will help.

Timer1, a 555 timer IC generates short pulses 10 times per second to trigger the HC-SR04 to send an ultrasonic burst.  This is the TRIG signal to the HC-SR04.  The HC-SR04 then generates a pulse output whose width is proportional to the distance to the target.  This is the ECHO signal and is a pulse stream at the 10 times per second rate.  The ECHO pulse width translates to 17cm/msec.  So if ECHO signal is 1 msec wide, the target is 17cm away.  If ECHO signal is 2msec, the target is 34cm.  Practically speaking, if positioned on the side of a track, a typical target (passing train) distance would be 5cm away so we're looking for pulse widths around 5cm/17cm x 1 msec = 0.3msec or 300 usec.

Timer2, half of a 74HC123 dual-monostable timer, generates an adjustable pulse width corresponding to the desired sensitivity or range of the sensor.  Since the sensor has a purported range of several meters, it will always be getting an echo from some part of the layout beyond the tracks.  In other words, the ECHO pulse width must be tested to find SHORT pulses meaning the target is only, say, 5-15cm distant.  The test will be to look for ECHO pulse width which are narrower than 300usec (5cm) - 900usec (15cm).  So Timer2 uses a trimpot to generate an adjustable pulse width that covers this range.

Timer3, the other half of the dual 74HC123 does the timing discrimination.  It compares the ECHO signal pulse width to the reference pulse width and if the ECHO is narrower than the desired target distance, it then generates a long pulse that turns on the SPDT relay.  The long pulse is settable in seconds just like the 153IR or ITAD.

It's that simple!  I show in the red circle what an Arduino or microcontroller could do.  You'd still need some kind of power supply to convert Accessory AC to 5V DC that the Arduino needs.  You'd still need some trimpots or method to adjust the distance-to-target sensitivity and the relay delay time.  And you'd still need some buffer to drive the SPDT relay.

Parts list attached.  The only non-jelly-bean (garden-variety) part is the relay.  The HK4100F is widely available and has 3 Amp contacts so plenty for a 153IR/ITAD type application.  Datasheet attached. 

Some effort was made to minimize the number of unique parts.  If your parts cupboard is bare and you're trying to build 1 or 2 to mess with, it will be oh so frustrating since minimum quantities, shipping, etc. will drive the cost thru the roof. 

Again, this is just a proof-of-concept.  I make no claims that this is better, worse, or whatever than any of our existing occupancy detection methods.  I suppose this would most likely be compared to the 153IR/ITAD Infrared methods.  In that regard, I'd think the occasionally reported issues/problems detecting IR/optical reflections off dark-colored surfaces would not be a factor for acoustic reflections.

OTOH, I only got 1 module to mess with, but I'm thinking there may be issues trying to use two or more of these in close proximity.  That is, the HC-SR04 sensor range is claimed to be several meters

Attachments

Not a dumb question at all.  The 5V circuit uses about 10mA when idle and waiting for a train.  Then about 50mA when the relay turns on.  With 14V/18V AC input:

When idle, 7805 input is about 19/23V DC.  So TO-220 dissipation is about 140/180mW; so that's no problem.

When active, 7805 input is about 16/20V DC.  So TO-220 dissipation is about 550/750mW; so yes, it does get a bit toasty but within spec.  So yes, I suppose you wouldn't want to mount the 7805 against a plastic wall or whatever.  Note that the 7805 input voltage drops when relay turns on because "only" half-wave rectification is used.

Believe it or not I thought about that - in trying to minimize the number of different components, you'll see there is another 220uF in the circuit.  220uF worked out well since it is not large enough to maintain the half-wave rectified DC level when the relay turns on and droops about 3V DC or so reducing the TO-220 dissipation by 150mW or so.  Every little bit helps!

Wow!  If you're really considering making a PCB design, keep me in the loop and post stuff here.  I'm sure I'll have comments.  I'd think the biggest stumbling block will be finding/making an enclosure.  The 2 trimpots have to be cleverly positioned for screwdriver access...though these tend to be one-and-done adjustments for a given layout.

Stan, thank you very much for drawing the schematic and posting it here.  Have you done any testing to find out how well the detection works with rounded objects (like tank cars and steam boilers)?

Also, curious about its ability to either detect and/or discriminate between the presence of trains on two or more parallel tracks, if the detector is either placed close to the first track or some distance further away from the parallel tracks.

For example, if attempting to use the detector to activate grade crossing signals for 2 or 3 parallel tracks, would one detector sense the presence of passing trains on any of those tracks and activate the signalling circuit if placed at a sufficient distance from the tracks?

As an opposing example, if the detector were placed close to to a mainline track for detection of a train heading into this mainline grade crossing, but there is also another nearby diverging spur track on the far side ~ 6" away from the closer detected track that doesn't cross the auto road, could a train on the spur be ignored by the detector?

@stan2004 posted:
Wow!  If you're really considering making a PCB design, keep me in the loop and post stuff here.  I'm sure I'll have comments.  I'd think the biggest stumbling block will be finding/making an enclosure.  The 2 trimpots have to be cleverly positioned for screwdriver access...though these tend to be one-and-done adjustments for a given layout.

Stan, you will most certainly be in the loop!  I'm entering the schematic into DipTrace now, and then I'll do a trial fit to see what size PCB will work.  Since I don't have that relay, and I already got bit by low current contacts, I'll be using the Songle 5V relay with 10A contacts.  I may have to improve the 5V supply.

That was fast!

1. Bridge is rotated.  AC inputs are going to the + and - terminals of the bridge.

2. Output of 1st 74HC123 should be pin 13 Q (not Q*).

And how about humoring me and plopping down the pads for the HK4100 relay.  I figure I'll be building one and presumably this shouldn't change the board size which I figure is what drives the raw PCB cost.  I guess you would need to build the part for your library.  In other words, just add a 2nd relay in parallel and the builder can decide which to install.  Note that the HK4100F is the relay used in the Lionel 153IR.

hk4100f alternate

Attachments

Images (1)
  • hk4100f alternate

OK, I noticed that not only was the bridge rotated, but I also left a surface mount part in the design.  But I didn't pick up that I used the wrong output on the HC123, good catch.

I'll have to look at putting in the pads for the HK4100 relay, given the large traces for the 10A model, that could be interesting fitting it in.  I didn't initially consider it as I also didn't have any of them on hand, and the only place I saw them was overseas with weeks of delay.

@stan2004 , I notice that there are two different pinout diagrams in the data sheet for the HK4100F, and they don't have any identification as to which matches what part number.  Which one of these is the "right" pinout?  Truthfully, I can't imagine why they needed two totally different base pinouts for the same specification part...

I'm "assuming" that the first one is the HK4100F and the second one is the HK4101F, but since there is no labeling of any kind on the two sets of base diagrams, I'm not 100% sure that assumption is correct.

 

This is the datasheet for the relay that I have: HK4100F-HUIKE.pdf

Attachments

Images (2)
  • mceclip0
  • mceclip1
Files (1)

Stan and John:

I'm glad that my suggestion on using a HC-SR04 in the model train world is a good idea.  I like how you're looking at ways to use this sensor without the Arduino.  Making a straight circuit with simple distance adjustments can make this sensor even easier to use.  Hats off to you both.  I'm working on a grade crossing circuit, which I'll post once I have finalized the code and sketch.  Thanks again from all us model railroaders. 😊🚂

@stan2004 , I notice that there are two different pinout diagrams in the data sheet for the HK4100F, and they don't have any identification as to which matches what part number.  Which one of these is the "right" pinout?  Truthfully, I can't imagine why they needed two totally different base pinouts for the same specification part...

hk4100f spdt

I see what you mean.  I'm after the 6-pin version.  The 2nd diagram (which I too assume is the HK4101F) has only 5-pins; and if you google HK4101F, pics show it to be 5-pin so I think that clinches it.

Attachments

Images (1)
  • hk4100f spdt
@SteveH posted:

... Have you done any testing to find out how well the detection works with rounded objects (like tank cars and steam boilers)?

Also, curious about its ability to either detect and/or discriminate between the presence of trains on two or more parallel tracks, if the detector is either placed close to the first track or some distance further away from the parallel tracks.

For example, if attempting to use the detector to activate grade crossing signals for 2 or 3 parallel tracks, would one detector sense the presence of passing trains on any of those tracks and activate the signalling circuit if placed at a sufficient distance from the tracks?

As an opposing example, if the detector were placed close to to a mainline track for detection of a train heading into this mainline grade crossing, but there is also another nearby diverging spur track on the far side ~ 6" away from the closer detected track that doesn't cross the auto road, could a train on the spur be ignored by the detector?

Haven't forgotten about you!  I figured I'd first attend to GRJ's efforts since getting a PCB would really move the ball down the field!

No, I have only done bench testing so that I could have all manners of instrumentation handy.  I have found the most useful tool at this proof-of-concept stage is the oscilloscope since I can watch each and every ECHO pulse and see how it changes in real-time as objects come in and out of reflection range.  But I just placed a Hudson boiler, a tennis ball can, and a coffee cup, with the sensitivity trimpot set to look for targets ~10 cm or less and they all tripped the detector within 1 cm of what a flat surface did.

I think it's the notion of setting the sensitivity as X cm or less that is novel. That is, with the speed-of-sound it is practical to  measure "time-of-flight" since the ECHO pulse width changes about 60 microseconds per cm.  Obviously trying to measure time-of-flight for the infrared method means measuring the speed-of-light which would not be practical!  As an aside, I suspect the next sensor idea might be an optical sensor that uses "auto-focus" like technology to estimate distance to objects.

Anyway, if parallel O-gauge tracks are, say, 10 cm apart (600 microseconds change in ECHO pulse width) it is not hard to imagine this amount of timing change can indeed be reliably discriminated.  I don't know if there's any application for this, but the "X cm or less" sensitivity setting means if you have 2 or more parallel track, this ultrasonic method can be reliably set to only trigger on the closest track (or the two closest tracks) and ignore anything further away.

As mentioned, the big unknown is the ability to use 2 or more of these in close proximity since the ultrasonic bursts are just sound waves and sound scatters rather well in air - unlike optical beams which stay in their lane.  Of course a downside of the ultrasonic method is it would NOT work in a vacuum whereas the optical method would!

I guess all that can be said so far is it's early days and we're trying to catch up to @sjbuff and his ground-breaking work!

GRJ, I did not see the part number of the trimpot but wanted to confirm it increase R with CW turn?  Measure-twice, solder-once!

Also, it looks like the 1uF capacitor after the 7805 disappeared?  I'd like some "bulk" capacitance on the 5V supply line near or midway between the timing IC chips even if your 3-pin regulator a small cap on the output side.

Stan, good call on the pots, I'll check again and make sure the rotation is correct.  One final thing I have to do is create a BOM once we think the design is laying flat.

As for the power supply, I used my switcher, but the same holes and pinout fit the LM7805.  There's room for that with an optional heatsink if so desired, so I think we have all bases covered.

I added two .1uf caps right across the two chips, my chosen method of bypass in most cases.  I got the second relay component mapped out and configured on the board.  I was having trouble putting it on top of the other one, so I just stuck it beside it.

I'll make sure about the pot connections and then post all the files again.  Here's a teaser of the 3D view as it stands now.  This should be as it looks completed, the wiring of the pots shouldn't change anything about positioning.  Too bad I didn't have a 3D model of the HC-SR04 to complete the picture...

Once we like the total design, I'll order some PCB's.

Attachments

Images (1)
  • mceclip0
@stan2004 posted:

Any way to place some mounting holes in the corners - maybe for #4 screws (holes about 1/8") ?

I don't know what 3D format you need, but if you google it there are downloadable 3D models of the HC-SR04.  For example:

hc-sr04 3d model

Stan, I could certainly look into some mounting holes, totally forgot about that option.  As for the 3D models, it has to be in a format that DipTrace imports.  The 3D modeling aspect is something I haven't spent a lot of time on as most of the stuff I do I can create a suitable model from existing parts.

Take a close look at the schematic if you will and make sure we're all laying flat there.  I'll make any other changes we need and put some holes in the corners for mounting posts.

Stan, Thank you for answering my questions about range and adjacent tracks discrimination.  John, thank you for working up the PCB layout.

Maybe something else to consider.  I'm wondering about the scenario of using this module for crossing gates and the benefit of having two detectors, one on each side of the grade crossing for trains approaching from either direction.

Also there is the notion of using this for block detection and having one or more additional detectors within and at the other end of the block.

Would it be possible to provide one or more inputs just prior to the relay trigger so that outputs of multiple modules could be wired together to activate the relay?  I see some advantages to this approach vs. just wiring the relay outputs from multiple modules together.

This may or course require a buffer between the Q2 output and the junction of D3 and the Relay coil.

Thoughts?

Last edited by SteveH

Stan, I'm ordering this from JLCPCB as it's six square inches and $30.  The whole order of 30 boards shipped DHL is $57, much easier to digest than $30 for three!  I'll send you some boards when I get them.  If you have a hankering to order some from OSHPark, here's the Gerber files.

HC-SR04 Ultrasonic Train Detector Gerber.zip

Attachments

What are you going to do with 30 boards?

I realize that's "only" $2/board but I really think just a few boards, even if $30 at Osh Park for 6 sq. inches, will help to get our arms around the packaging.  I really think the enclosure will be a stumbling block and should/will drive the board layout.  Again, I will gladly pay the $30 ($10/board) and send you 1 to mess with...

Well, the order is in, Since the DHL shipping was the lion's share of the order, I just bumped it from ten to thirty.   Too late to make a change on this one.

I also wanted 2oz copper for the relay traces, and with OSHPark you have to go to the thin board for that option.  This isn't a candidate for thin boards, at least IMO.

Last edited by gunrunnerjohn
@SteveH posted:

...
Maybe something else to consider.  I'm wondering about the scenario of using this module for crossing gates and the benefit of having two detectors, one on each side of the grade crossing for trains approaching from either direction.

...
Thoughts?

So my thoughts are:

1. The 5-wire crossing gate.

2%20or%20more%20scaletrax%20ITAD%20with%202%20or%20more%20crossing%20gates

As you describe there is an application where either detector should trigger a crossing gate.  And if the crossing gate is the 5-wire style, you can't simply parallel the NO and NC relay outputs as they would fight each other if only one detector is triggered.  So the "standard" answer is an external arbitration relay.  And since this can be done for around $5 DIY (like above) or $10 with an off-the-shelf relay, I too thought about this but want to focus on the detection sensing technology.

So yes, some kind of "party-line" connection could be made between 2 or more detectors so that if ANY detector is active then a chosen relay would trigger.

AFAIK, the latest Lionel incarnation of the crossing gates has only 3-wires.  This only requires a connection to the relay NO of the detector...and all the NO contacts can be paralleled without an external arbitration relay.

2. Judicious choice of the "DELAY" time.

The 153IR and MTH ITAD detectors have the Delay adjustment to keep the relay triggered 10 seconds or more after the detected object passes.  The DELAY gives the consist time to reach the other detector.  Obviously you could stop the consist right on the crossing with the caboose 1" beyond the detector and the gates would go up.  Well, don't do that!

3. Latching detector.

Can't recall if it was the current thread but the idea of the gates going down when, say, the East side detector is triggered...but then don't go back up until the West side detector is cleared.  That is, if you have just an engine it is likely the engine will be between the two detectors for some interval during which the gates go up.  So perhaps a mode where the relay latches when either detector triggers, and then unlatches only after the other detector is triggered and cleared.  And this should support bi-directional travel.  Well, this design obviously doesn't support this.  I suppose a basic latching mechanism as described could get "fooled" if a consist trips the East detector...stops...and then backs up never reaching the West detector at all.  In which case maybe the DELAY timer comes into play to release the gates after some settable time interval.

---------

Anyway, just wanted to jot down my thoughts.  Yes, the tried-and-true insulated-rail method does not have any of these issues...but then again this is more fun discussing new ideas in our hobby! 

Attachments

Images (1)
  • 2%20or%20more%20scaletrax%20ITAD%20with%202%20or%20more%20crossing%20gates
Last edited by stan2004

My vision was once the east trigger activated the gate crossing,  the crossing gates lower and lights would flash until the next phase is triggered by west sensor. At this point the gate would not default to clear until the west trigger sensor completes its process.  I know in the Arduino code I use a command called (switch case) where each case is a particular event.  When one event begins ( lights and gates activated ) the microprocessor will continue to loop back in the code to look at all the possible switch case options and pending the input of the HC-SR04's the switch case would advance to the next option.  Using a relay to trigger NO or NC, I'm not sure you can get the same results as switch case scenario.  A calculated delay would be needed when switching the relay.

I am really looking forward on the prototype, and seeing what becomes of this circuit.  Fantastic job you guys, running with this..  👍

Well it was a bit awkward to set up but here's a scope video showing what I consider to be surprisingly stable and reliable ECHO pulse timing.  In other words, I believe what I'm seeing. 

The scope is displaying 10 pulses per second.  It takes a while to appreciate what is going on here!  This is measuring distance in real-time. 

I'm wondering if there are other O-gauge applications that could benefit from the ability to reliably measure distance to an object - perhaps for some TBD animated accessory?

That is really cool! 👍 Yes to measure in real time.  I was also thinking to sense a train coming into a station for example and have a station announcement be triggered.  Or when a train out of view has cleared a particular area, trigger a location icon on a control panel, there's a bunch of things that this circuit could be used for. 

On the question of 40kHz interference amongst multiple HC-SR04 units, John's idea of a detector link that would stagger the transmitted pulse outputs among multiple units is intriguing.

Another alternative would be in the physical realm. There are a multitude of inexpensive porous acoustic absorbers which should be effective in this frequency range.  For example, mineral wool, natural fabrics, etc.  At this frequency, it should require little material thickness to effectively adsorb the propagated signal and prevent nearby detectors from interfering with each other.

Stan, would you be interested in seeing if this theory is applicable by placing something like a couple of layers of denim between the detector and another reflective object to see if the signal is adsorbed?

OK.  I'm game for a snipe hunt!

denim and black component foam

So if I place 1 or 2 layers of denim (from a pair of jeans) in front of sensor, it simply reflects back and the sensor detects it.  I have no way to quantify how much acoustic energy went thru the denim since the ECHO pulse width drops to the distance to the denim.

OTOH, if I place a 1/2" thick piece of black antistatic ESD foam, the acoustic energy goes thru.  So a target beyond the foam is what gets detected.  Some of the energy is getting absorbed or dispersed since the ability to detect objects beyond the foam is reduced.

Not sure if this is what you're after but it is interesting how the antistatic foam is like glass to an infrared beam.

Attachments

Images (1)
  • denim and black component foam
Last edited by stan2004
@stan2004 posted:

OK.  I'm game for a snipe hunt!

So if I place 1 or 2 layers of denim (from a pair of jeans) in front of sensor, it simply reflects back and the sensor detects it.  I have way to see how much energy went thru the denim since the ECHO pulse width drops to the distance to the denim.

OTOH, if I place a 1/2" thick piece of black antistatic ESD foam, the acoustic energy goes thru.  So a target beyond the foam is what gets detected.  Some of the energy is getting absorbed or dispersed since the ability to detect objects beyond the foam is reduced.

Not sure if this is what you're after but it is interesting how the antistatic foam is like glass to an infrared beam.

Infrared beam?  You've been working with that other technology too long!

Stan, you get an A+ on today's lab experiment, plus extra credit.   I'm a little surprised that the denim is so acoustically reflective at 40kHz.  Conventional wisdom in the applied acoustics field indicates that denim should be very absorptive throughout the higher audible frequency range (2.5k-20kHz).  But based on practical applications and personal observations, I have often wondered if that may be incorrect when it comes to frequencies above 10kHz or so.

As an example, most Noise Reduction Coefficient charts claim an essentially flat NRC around 1 above 4kHz for most absorptive materials (1 being 100% absorptive and 0 being completely reflective).

Based on your findings it seems clear that denim is in fact too dense to absorb much of the 40kHz energy produced by these transducers.  It is possible that a softer looser weave cotton material like fuzzy flannel or uncompressed yet sufficiently thick multi-layered gauze could be more absorbent at 40kHz.

It may also be that the wave energy intensity, especially close to the transducer (see inverse square law for sound) would be too intense for effective absorption without going to extreme measures.

It's also possible that discovering an ideal inexpensive material that would be easy for most people to implement is probably well described (in your words) as a snipe hunt.  Thanks again for contributing to the greater knowledge base here on the forum.

@sjbuff posted:

HC-SR04 Ultrasonic Sensor

Train Detection Block Signals

I thought I share the use of this ultrasonic sensor, I was able to utilize the sensor in my outdoor dead rail layout as a train/block detection on my layout.

Since converting the Baldy & Palms Railroad to “dead rail” in early 2021, the track detection circuit on the upper loop has been functioning correctly about 80% of the time.  The reed switch circuit would get triggered by the magnets at one end of the block and not at the other end.  This made the circuit go out of sync.  I decided to try several other sensors with the Arduino to find a suitable solution. I tried the current sensor, voltage sensor, relay circuit, and the IR sensor, none of these performed reliably.  

E5AAA3D6-6672-4723-A343-8FA647551FB3CC6447FA-7E70-465F-A3A1-868B85D6BD7A67884DD9-A5F2-4578-9331-ACD003FE76B0I discovered the HC-SR04 ultrasonic sensor and decided to experiment with this sensor.  I also created a better Arduino code with the HC-SR04 sensor.  I adapted the HC-SR04 sensor to fit in a small signal shed to match and blend with the block signal.  The Arduino code is written so the HC-SR04 monitors motion from about 4 to 8 CM across the track. When a train is detected on one end of the block, the signal will turn red, and remain red until the train exits the other end of the block, at which the signal will reset to a clear green signal.  This can be used with two or three aspect signals.  The code just needs a few lines of code activated. The circuit has performed very well, so I plan to incorporate this circuit in other trains detection blocks on the layout. Check out the YT video for the Arduino code sketch and circuit design.   YT Video - HC-SR04 Block Signal

Hope this post helps other outdoor layouts having the same problem and eliminate the need to put magnets on locomotives and rolling stock.

I must ask this question, in G scale we use a simple magnet reed switch and timed relay for our trains. Works great and the switch just drops between the rails.

@stan2004 posted:

Thanks for the BOM; I needed to confirm the footprints on various parts so I could order what I didn't have.  I supposedly just made the cut-off for parts from China as their New Year shutdown week is starting.  We'll see...

I needed to generate that anyway, so it was no big deal.  Hopefully, the boards made it before the New Year cutoff, they're coming from China as well.

Looks like they're making them anyway...

Attachments

Images (1)
  • mceclip0
@ThatGuy posted:

I must ask this question, in G scale we use a simple magnet reed switch and timed relay for our trains. Works great and the switch just drops between the rails.

Yes - I've been using the reed switch/magnet for awhile now, and received mixed results.  Magnet would not trigger the reed switch often.  In my case once the magnet triggered the signal, the other end of the block would trigger the signal back to clear.  If the reed switch missed the trigger, the block would not clear. I found the ultrasonic sensor more reliable in my situation. 

Getting closer, the boards are completed, they should be shipping them soon.  I should have them within a week if DHL is awake.

I think my parts might just beat you to the finish line.  I see that JLCPCB and LCSC.com (where I ordered parts) are affiliated and perhaps the same company.  In any case I ordered the parts when you ordered the boards.  My tracking suggests the package did come by air and is somewhere in the US presumably to be given to USPS.

lcsc tracking

Meanwhile, I was hunting around and am astonished by the wide distribution of the HC-SR04 module.

hc-sr04 prices all over the map

Amazon has multiple sellers.  eBay has multiple sellers - and even multiple sellers at 78 cents with free shipping from Asia (takes about 2-3 weeks).  Even DigiKey is/was in the game though I think it was more a "convenience" item given their pricing.  I think there must be some factory in Asia cranking these things out as fast as they can!

Anyway, since we're cooling our heels waiting for stuff, on separate note, I am comfortable recommending LCSC.com for componentsif you aren't in a rush.  In this project, I knew the boards wouldn't be here for a few weeks, so I was able to find a single-source for components I did not have in GRJ's BOM.  First off, to be clear, I am a fan of DigiKey and have been purchasing components from them for over 40 years!  Here's a fun photo of a sample of my DigiKey packing slips! 

digikey orders

I'm only talking about hobbyist orders and prototyping quantities...I don't have anything useful to say on comparing LCSC vs. DigiKey for production ordering (quantities in the thousands or millions).

I compared pricing for some parts in the BOM. I was too lazy to figure out how to make a neat table but here's the qty 10 pricing for LCSC vs. DigiKey:

0.022 capacitor    12 vs. 17 cents

220uF capacitor    7 vs. 22 cents

200K trimpot     9 vs. 40 cents

555 timer IC     16 vs. 32 cents

7805 voltage IC     23 vs. 52 cents

2-pin screw terminal    13 vs. 53 cents

G5LE 10A relay    $0.60 vs. $1.57

eBay (Asia seller) will typically offer better pricing on any given component.  But when you need a variety of parts in small hobbyist/prototyping quantities, it is a nuisance and roll-of-the-dice to buy one part here, one part there, from multiple eBay sellers.  Like DigiKey you will be overwhelmed by the LCSC.com website when you get inundated with hundreds or thousands of choices for a simple component description...and then struggle to narrow down the choices via sometimes cryptic selector columns.

Bottom line.  I've noticed a lot more interest/ability for guys on OGR designing their own PC boards.  I suppose a lot of this is from the low-cost fabrication options like OshPark and free PC board design software. That said, and given that it typically takes 2 week or so to receive boards (unless paying usurious expedite fees), perhaps it's worth a look at LCSC.com for components. 

Attachments

Images (3)
  • lcsc tracking
  • hc-sr04 prices all over the map
  • digikey orders

Looks like the boards have shipped as well.  Apparently, DHL just thinks shipment info received, so I'll probably have it in about 3-4 days.

Thank you for your order from JLCPCB. It’s our pleasure serving you. We are pleased to inform you that the items listed below have been shipped via DHL International Express. Tracking Number: 9975697034,

Attachments

Images (1)
  • mceclip0

Thanks everyone involved in making the pcb board and components list. Here I thought I found a good solution to eliminate the need of a IR sensor in an outdoor environment, never would I thought this could be a viable solution to substitute the IR153, and the use of this circuit without needing an Arduino is awesome for the average railroad modeler. Hats off to all. 👏👍🚂

Well guys, let's not count them chickens before they hatch!   I'm thinking it would be useful to get prototypes in the hands of some interested parties who would be willing to actually mess with it on their layout.   Like those late-night TV ads for some medical device, I believe it would have to be one of those "at little or no cost to you" deals though Medicare would not be required.

All the occupancy detection schemes have their plusses and minuses.  I think part of the fun with alternative technologies like ultrasonics is the adventure of finding new applications.  I think the precise distance discrimination/sensing capability might have as of yet undiscovered applications in running out trains!   

I remain baffled as to how the HC-SR04 module on eBay is 78 cents (free shipping from Asia) and includes a tracking number.

@stan2004 posted:
I remain baffled as to how the HC-SR04 module on eBay is 78 cents (free shipping from Asia) and includes a tracking number.

Stan, it amazes me at the costs of some of the stuff from China, small wonder they're eating our lunch!  I'm just afraid when they finish our lunch, the gravy train will pull into the station and stuff will get VERY expensive!

Here's the "first look" at an assembled PCB for this unit.  I have to say, works pretty well!  It's closest range appears to be 3-4 inches and the longest range was around 3 feet.  This was strictly preliminary testing saving a boxcar around.  Plug-n-play, it ran right out of the box.

I used Stan's choice for the relay, it's a 3A model.  You'll note the blank space for a 10A relay, you can mount either one.  I'm using a 5V 500ma switching module that I use on a number of products, but you can also use the LM7805T regulator in that spot as well.

I give a big hand to Stan, it worked as advertised just copying his schematic and plopping it onto a PCB.

HC-SR04 Ultrasonic Train Detector 1st PCB

Attachments

Images (1)
  • HC-SR04 Ultrasonic Train Detector 1st PCB
Last edited by gunrunnerjohn

As expected, there is interference when two of these can see each other.

I started out with the obvious configuration below.

I set the range to sense about 6-8" and fired the two up.  About every 15 seconds at a somewhat random time, one or both would trigger.

Next I pointed them at a 45 degree angle at the parts cabinets you see at the top of the shot, and it was pretty much the same, slightly less often I'd say.  Finally, I moved them about 4 feet apart and pointed at the cabinets or straight on they still triggered in a similar manner.

The last test was point them out where there was about 7-8 feet to the first obstruction, they didn't trigger at that point, at least for around 10 minutes.

An obstruction placed in front of one but out of the sensing range did seem to block the signal and the other unit stopped randomly triggering.

Obviously, the use of these would have to meet some guidelines on positioning.

OTOH, they seem dead reliable triggering on a lot of different surfaces.

Attachments

Images (1)
  • mceclip0

John, those turned out very nice!  Too bad they interfere with each other.  Wonder if some type of a trackside enclosure would help the interference, maybe narrow the sensing area or something. Still quite useable for many things though.

If you are planning to sell any of those PCBs, I would be interested in at least two of them. I have some of the HC-SR04s I got a couple years ago for something else and never used. And thanks for creating and testing!

Any obstruction that blocks the path appears to knock down the interference, and once I turned them to where there wasn't anything to reflect the beam for a few feet, they no longer had a conflict.  I was impressed on how well they ranged, if you had the sensing distance at about 6", anything at 9" didn't trip them at all.

I think what is behind what you aim them at is a primary factor in their interference.

I did order complete sets of parts and found some terminal blocks for the connections.  I'll have to wait for the Far East, getting the chips from my common sources was not possible, all the major houses were out of them.  eBay wanted a King's Ransom for the 'HC123 chips.

A better mousetrap has always been the bane of DIY invention!

I am just about done with my "phantom" occupancy detector.  That is, any self-respecting modeler built the phantom/transparent P-51 when it came out 50 years ago or so!

phantom ultrasonic detector

My idea is like the traveling O-gauge boxcar from a few years back.  My thought is I will send this to a fellow OGR member who would try it on their layout and give us feedback.  I will pay the $5 shipping.  Then, the next guy does his thing and writes up comments/observations on OGR and sends it to the next guy paying the $5 shipping.  And so on.  At some point I guess it comes back to me.  What I see is a DIY collaboration to experiment with a "new" occupancy-detection technology without the nuisance of ordering components, soldering boards, and so on.  Masks not required.   Anyone interested???

Separately, I commented earlier that packaging is a practical issue.  The ultrasonic module is kind of unusual and may be difficult to embed in a trackside utility cabinet or whatever.

ultrasonic split

So what if the HC-SR04 module can be placed in a simpler housing that sits trackside...and there are 4-wires that go to the electronics board that sits below the layout.  I realize I'm stumbling over my own words but I don't think it's practical to fabricate an odd-shaped trackside cabinet that is realistic...even with a 3-D printer.  The Lionel 153IR occupancy detector is quite an unusual shape; and IMO it doesn't even look like a realistic layout accessory.

I'm thinking it would be much easier to fabricate an above-ground cabinet for JUST the HC-SR04 module....and then run 4-wires to the electronics which can be the circuit board without an enclosure as it would sit below ground (under the layout).  Again, feedback???

Attachments

Images (2)
  • phantom ultrasonic detector
  • ultrasonic split
Last edited by stan2004

Add Reply

Post

OGR Publishing, Inc., 1310 Eastside Centre Ct, Suite 6, Mountain Home, AR 72653
800-980-OGRR (6477)
www.ogaugerr.com

×
×
×
×
Link copied to your clipboard.
×
×