Detecting Trains with IR Sensors, Part II
This is going to be a short post: it’s working! I have my IR LED phototransistor sensor program detecting things (not trains just yet), and I’ve posted the example code, see the bottom of the Tram Controller page for a links to that, and the earlier motor control code. Both example programs are public domain, feel free to use them however you see fit. I’ve benefited from a lot of public domain programs, and I think it’s only fair to give something back. When the tram controller program is a bit more polished, I plan to publish it in the same way, although it may be months before I get to that point.
I’ve chronicled my work in getting these sensors working on my Sensor Testing page, along with an updated circuit diagram, so I won’t restate that material here. You can also read earlier Musings on this topic via the Tram Controller category link.
I will share one interesting thing I did in the course of this. While trying to find a bug (which was ultimately a stupid coding error) I thought that the smoothing algorithm wasn’t working correctly. So I wrote a simple test program that stored several hundred raw and smoothed sensor values in an array, set it up so I could capture a sensor going occupied or unoccupied, and have it spit out the numbers after catching the transition in real time. I then stuck the numbers in an Excel spreadsheet to graph them.
I used these to graph both the original smoothing algorithm I’d found (green line) and the one I was using (red line), along with the raw readings from the sensors (blue line). Here’s what I saw over the course of 20 samples taken at 1.5 millisecond intervals:
Sensor being blocked
Sensor going clear
The raw sensor rise wasn’t always that fast, but it often was. And the graphs proved that my sensors were working as expected, and that my smoothing algorithm really was doing a fast exponential average smoothing of the sensor values, exactly as expected.
As for my example program, I ran it in dim light, and under the full glare of a halogen desk lamp 18” (0.5m) above the sensors shining directly down on them at full intensity. In both cases, using 2 Kohm resistors for the analog pins, the program read correctly every time. In the halogen lamp test, I also passed my hand slowly across the top of the sensors, blocking the halogen light but not the LEDs, and the sensors did not give me a false positive. I won’t guarantee they’re immune to interference from ambient light, but they seem to work quite well for me. More testing is, of course, planned.
So that’s it, just a quick update on my success this week. I hope you find it useful.