"Calibrating" LDR using a separate "ambient" LDR

Afternoon folks,

I'm looking to use LDRs to detect the presence of trains on a model railway - the LDRs would be mounted between the rails, reacting to the shadows cast by the trains as they roll over.

As the layout being built is going to be travelling to various exhibitions, likely with varying lighting conditions, I was thinking of using an extra LDR mounted away from any rails to measure the ambient lighting conditions, which would then "calibrate" the other LDRs to react correctly.

In my mind, this seems like a reasonably straightforward thing to do... but then I sit down in front of PE6 and try to type it out! Does anyone have any ideas on how this could be achieved?

Cheers!
 

premelec

Senior Member
LDRs are mostly pretty sloppy unit to unit - that said its worth a try to have 2 "identical" LDRs in series with ends going to V+ and V- and one between tracks and other above train and watch the junction point between the 2 LDRs which should be about 1/2 V+ when both exposed to same light... could be trouble with shadows etc... project might be better with magnets and hall effect sensors etc... or not because of stray fields... ;-0
 
LDRs are mostly pretty sloppy unit to unit - that said its worth a try to have 2 "identical" LDRs in series with ends going to V+ and V- and one between tracks and other above train and watch the junction point between the 2 LDRs which should be about 1/2 V+ when both exposed to same light... could be trouble with shadows etc... project might be better with magnets and hall effect sensors etc... or not because of stray fields... ;-0
Not 100% sure what you mean by the first half there - you've lost me unfortunately...

And yes, magnets / reed switches / hall effect sensors would be a more reliable solution, but it requires modification of the models - and as this is a club layout, the aim is to make it work with any rolling stock, modified or not - you don't need to modify a train to make it cast a shadow!
 

AllyCat

Senior Member
Hi,

Yes it should be possible to make your LDRs work, If you have multiple "track" sensors and only one "reference", then each needs (typically) a pull-up resistor to the supply rail (with their junction to an ADC input).

If you make the "reference" pullup say 10 k and each of the "track" pullups two or three times larger (e.g. 22k - 33k) then you may be able to directly compare the ADC values, e.g. .IF ADCtrack > ADCref THEN : Train_is_Present An advantage of using pullup resistors of around 30 k is that you could use the internal "Weak PullUp Resistors" of most PICaxes (and probably the Low side of the LDRs can connect directly to the track).

Cheers, Alan.
 
What you want to do is differentialy detect the train with two sensors in line.
Not really... I'm not interested in which direction the train is travelling, only that a train is physically present - there's going to be multiple points on the layout which aren't easy to see from the "normal" operating position, so these simply serve as a visual indication to the operator that the train has arrived where he desires.

Yes it should be possible to make your LDRs work, If you have multiple "track" sensors and only one "reference", then each needs (typically) a pull-up resistor to the supply rail (with their junction to an ADC input).
So the opposite of what's in the Manual 2, which shows a voltage divider with the LDR between 5V and the PICAXE, the a pulldown resistor between the PICAXE and GND?

If you make the "reference" pullup say 10 k and each of the "track" pullups two or three times larger (e.g. 22k - 33k) then you may be able to directly compare the ADC values, e.g. .IF ADCtrack > ADCref THEN : Train_is_Present An advantage of using pullup resistors of around 30 k is that you could use the internal "Weak PullUp Resistors" of most PICaxes (and probably the Low side of the LDRs can connect directly to the track).
Just a note on this - when it comes to the "final deployment" of these, I'll actually be operating at 3.3V, with the PICAXE chips acting as a slave to a Teensy - the PICAXE will be dedicated to the LDRs, on an i2c bus with the Teensy... not sure if the voltage difference will make too much difference.

As for the actual pullup values, I'll do some experimenting tonight - I'm putting together a test board, as I don't have access to a computer at the club - simply 6 7-segment displays showing the values of two LDRs at once (8-bit ADC) - which I can use to test out a couple of different resistor values, see what I can come up with...

Cheers!
 

premelec

Senior Member
Empiricism is your friend... try it out... using 2 LDRs as I or techElder suggest compensates some for changes in ambient light - however you can use an LDR and Resistor to look for ANY change... BTW you might want to put a small capacitor on ADC input pin to V- Some LDRs have very fast response some slow... capacitor would stretch the the input signal time wise and perhaps deal with ambient flicker from line frequency or other sources...
 

hippy

Technical Support
Staff member
It should be possible to calibrate each track sensor without using any other. While the sensor isn't covered you can determine an average baseline ambient light level and then determine when the sensor goes dark from that. Something like the following -
Code:
Symbol LDR_PIN    = C.1

Symbol total      = w1 ; b3:b2
Symbol samples    = w2 ; b5:b4
Symbol ldrReading = b6
Symbol average    = b7
Symbol darkLevel  = b8

Do
  ReadAdc LDR_PIN, ldrReading
  If ldrReading < darkLevel Then
    SerTxd("Covered", CR, LF )
  Else
    If samples = 256 Then
      total = total - average
    Else
      samples = samples + 1
    End If
    total = total + ldrReading
    average = total / samples
    darkLevel = 80 * average / 100
  End If
Loop
You will need to alter some things if the LDR reading goes up when it gets darker, but can test with a torch rather than covering the sensor if it doesn't work first go.

The number of samples and percentage change may need to be tweaked but I would expect it should generally work. Worked reasonably well when tested with a pot.

Added : If the sensors are out of sight it might be possible to put a bulb or LED above the track and use the LDR as a simple break-beam detector, so no need for anything complicated just whether the reading is above or below a certain level.
 
Last edited:

techElder

Well-known member
I'm not interested in which direction the train is travelling
Well, me thinks thou doth dismiss too quickly! :D

Differential LDRs will both see the same light until one of them doesn't. That means a train is passing over them. First one; then the other. Plenty of time to differentially detect the difference and set off the signal. Space them about half the length of the shortest car in line down the middle of the track.
 

erco

Senior Member
I'm betting you can do it without even using ADC if you put a pair of photocells in series as described. Both photocells are pointed up, #1 in shadow under the train, connected to V+ and #2 beside the track in the open (no shadow) connected to ground. It's a voltage divider so you'll get half voltage at the junction (fed to any Picaxe input pin) with no train present. Half of 3.3V is 1.65, which will read "HIGH" to the Picaxe. With #1 in the train's shadow, junction voltage will fall well below 1.4V and will read LOW. It stays LOW anytime any part of the train blocks photocell #1.

techElder's idea of inline photocells can work here too, except there will only be a brief LOW signal when only #1 is blocked/dark and #2 open/bright. This only works properly (as intended, sensing the engine) with the train moving in one direction. Moving in the other direction, the brief LOW signal senses when the caboose clears photocell #2.
 

AllyCat

Senior Member
Hi,
So the opposite of what's in the Manual 2, which shows a voltage divider with the LDR between 5V and the PICAXE, the a pulldown resistor between the PICAXE and GND?
Yes, because the manual circuit was probably arranged to give a rising ADC value as the brightness increased. But here your detection criterion is "darkness" so it's sensible for that to generate the logical "true" (1) level.

Of course it's easy to invert logical or ADC values (e.g. IF ADCtrack < ADCref..) so the real advantage of putting the LDR in the Low side is hardware simplification. You don't need to take the (3.3v) supply rail to the LDRs and perhaps can use the "Ground" of the track itself, so need only one wire.

I really don't see the advantage in using two LDRs when one will do! In fact hippy is right that it may be better (not to use a reference LDR and) for the software to just keep a "rolling average" of the light level at each LDR and look for a sudden dip in the light level (or rise in the ADC value).

Two other issues with the ideas of using two LDRs in series: At 3.3 volts supply, the minimum Logic 1 input level of the PIC{axe} is 1.6 volts (i.e. 0.8 + Vcc/4) which is very close to the half way level; much closer than the probable balance between two random LDRs. Also, I wondered what is the minimum resistance of an LDR: RS Data Sheet 232-3816 shows one falling to 100 ohms at 10,000 Lux, but bright sunlight is over 100,000 Lux so might the resistance go even lower?

The 30k Weak Pullups will limit the current to 100 uA for each LDR and a READADC10 could resolve down to 30 ohms. In fact the Microchip data sheet implies that the first ADC step is LSB/2 so perhaps even 15 ohms (if the LDR is on the Low side).

Cheers, Alan.
 

techElder

Well-known member
techElder's idea of inline photocells can work here too, except there will only be a brief LOW signal when only #1 is blocked/dark and #2 open/bright.
If I wasn't preparing for a long trip out of town, I could work on this better. I believe I've done it before with an 08, so that means I've probably lost the circuit/program somewhere.

To be more clear, I'm not proposing a series combo of LDRs. I'm proposing to use two inputs with two LDRs. Detecting the shadowing of either LDR with the input threshold of a digital input.

That doesn't mean that one can't use two analog inputs to do the same.

Theoretically, you could determine direction, but the OP says nope.
 
Well, this is what I get for having a good night's sleep... line up everyone, one at a time please! ;)

Well, me thinks thou doth dismiss too quickly! :D
Lol, now that you've explained it yes - I most definitely did dismiss too quickly! One for the swear jar methinks...
Differential LDRs will both see the same light until one of them doesn't. That means a train is passing over them. First one; then the other. Plenty of time to differentially detect the difference and set off the signal. Space them about half the length of the shortest car in line down the middle of the track.
Yes, that definitely does make sense... bearing in mind this is N gauge (1:148), I would probably have them approximately 25-30mm apart, which is about half the length of the shortest locomotive / wagon.
Thinking about it (dangerous, I know!), that also introduces two additional useful features - direction detection (as mentioned) and precise position detection. These will be useful, as one part of the layout will be automated (it's just a pair of circular tracks with three loops for stabling trains), and as they're controlled using "traditional" 0-12V DC and relays, I can use those extra LDRs to detect whether the train is a) moving in the correct direction, and b) moving at all - they can and will stall on dirty track occasionally, so by this means I can detect it...
techElder, your brain is a dangerous weapon, giving me ideas!! ;)

Added : If the sensors are out of sight it might be possible to put a bulb or LED above the track and use the LDR as a simple break-beam detector, so no need for anything complicated just whether the reading is above or below a certain level.
Well yes, most are going to be in the "fiddle yard", ie out of the "public view" - so a simple "lighting gantry" would be easy enough... and definitely more reliable! There's only a few "outside" in the scenic area where they need to be relatively well hidden, so they're the "difficult" ones!

And finally, the mentioning of using digital inputs instead of analogue - to be honest, I'm not going to have too many of these in one place to necessitate rationing GPIO - as each 2x4' baseboard has its own "logic board", each one is essentially self-sufficient. So unless I suddenly have a silly number on a single board, GPIO availability isn't going to be a problem :) Currently, even if I use techElder's idea of using pairs of LDRs, I would have a maximum of 22 LDRs on any one board - the 40X2 has 25 available ADCs (excluding the i2c pins), and at £5.60 a chip it's not a massive investment... and there's no additional cost to include a footprint for a smaller PICAXE on the PCB for less-populated board!
 

erco

Senior Member
Many ways to skin this cat. Certainly worth experimenting since photocells/LDRs are practically free these days: https://www.ebay.com/itm/142062774416

FYI, here are some related videos of mine.

Using a voltage divider input (POT here could be replaced by 2 photocells) and sensing HIGH/LOW without using an ADC. 4.5V supply voltage, 1.3V transition voltage:


Sensing light/dark direction using 2 series photocells with a ADC:



 
As an addition to the current trains of thought - having presented this conundrum to a friend, he actually suggested doing away with the PICAXE altogether, and using I/O expanders and digital inputs as described above...

Provided I use "proper" light gates instead of *only* LDRs, I could use a simple pot to adjust the input sensitivity, with the digital inputs of the I/O expander being toggled on/off. Then a simple interrupt wire to the main Teensy controller (chosen due to its high processing capacity, low cost, size of program memory, native SD support, native CAN support and number of GPIO), so it can interrogate the I/O expander at the appropriate time...
 

erco

Senior Member
Jumping Picaxe ship so quickly after all these helpful how-to posts? Jeepers. Next time, please ask your friend before posting.
 

hippy

Technical Support
Staff member
he actually suggested doing away with the PICAXE altogether, and using I/O expanders and digital inputs as described above...

Provided I use "proper" light gates instead of *only* LDRs, I could use a simple pot to adjust the input sensitivity, with the digital inputs of the I/O expander being toggled on/off.
The potential problem with that approach is you lose the automatic adjustment and you won't know it needs adjusting until it starts missing detections. You may also need an adjustment per sensor.
 
Jumping Picaxe ship so quickly after all these helpful how-to posts? Jeepers. Next time, please ask your friend before posting.
Wow... so much hate...

That, my friend, was an additional thought - I still don't know if I'm using PICAXE, Teensy, Arduino or bare PIC/AVRs... depending on the size of the application it could be any of them... And besides, I suspect that given the low cost of a PICAXE, lazy me will probably still use them instead of I/O expanders - I already know how to communicate with them using basic i2c comms, and they give me extra flexibility in terms of detection.

I always was going to use a Teensy as the primary logic board in this application - it has on-board CAN, which I need to interface with the wider system - this question regards the Analogue side of things.

The potential problem with that approach is you lose the automatic adjustment and you won't know it needs adjusting until it starts missing detections. You may also need an adjustment per sensor.
Aye, that's true... the question is then, would adjustment be necessary at all (once set up initially of course) if you're using a light gate? LEDs above the track, sensor between the rails, train passing between them casts a shadow... Not being familiar with LDRs I'm not sure how much of a difference that would make
 

hippy

Technical Support
Staff member
would adjustment be necessary at all (once set up initially of course) if you're using a light gate? LEDs above the track, sensor between the rails
Probably not. That should give readings, light blocked and not, which have enough separation to distinguish the two.
 

AllyCat

Senior Member
Hi,
... most are going to be in the "fiddle yard", ie out of the "public view" - so a simple "lighting gantry" would be easy enough... and definitely more reliable! There's only a few "outside" in the scenic area where they need to be relatively well hidden, so they're the "difficult" ones!
So what about the "public view" ones, and how high and variable might the ambient light level be for any or all of them? For example, is there any risk at all of direct sunlight through a window or skylight at any time?

For an "invisible" (to the public) light gate you would normally use Infra Red, and for high light levels some modulation of the light level (on-off at a high frequency). But beware that LDRs are NOT generally sensitive to Infra Red ("same response as the human eye") and usually have a poor High-frequency response, so may not be responsive to "invisible" (to the human eye) modulation.

Another possibility might be a "reflective" IR gate (i.e. upward facing LED and photodiode) in the track. Assuming the issue of ambient (Infra Red) "light" is taken into account (e.g. using modulation) then normally the sensor will receive "no" light, but it would be reflected/diffused back down from the underside of the train, even if it is notionally "black".

But this all seems to be getting very complicated, compared with your original proposal (particularly as refined by hippy to use an average for each sensor). Basically, all you need is a single LDR in the track, connected by one wire to a PICaxe pin running a simple averaging algorithm for each track-location (so no physical "reference" or "calibration" is needed). Two adjacent sensors at any location then could be a refinement to infer the direction of movement, if so required.

Cheers, Alan.
 
So what about the "public view" ones, and how high and variable might the ambient light level be for any or all of them? For example, is there any risk at all of direct sunlight through a window or skylight at any time?
Unfortunately, the "public" ones will have to deal with pretty much anything... this is an exhibition layout, so it will be operated in different locations, halls etc. There's at least one I can remember which has skylights and problems with sunlight...

For an "invisible" (to the public) light gate you would normally use Infra Red, and for high light levels some modulation of the light level (on-off at a high frequency). But beware that LDRs are NOT generally sensitive to Infra Red ("same response as the human eye") and usually have a poor High-frequency response, so may not be responsive to "invisible" (to the human eye) modulation.

Another possibility might be a "reflective" IR gate (i.e. upward facing LED and photodiode) in the track. Assuming the issue of ambient (Infra Red) "light" is taken into account (e.g. using modulation) then normally the sensor will receive "no" light, but it would be reflected/diffused back down from the underside of the train, even if it is notionally "black".
You know something? I'm a numpty. I've always liked the look of the combined IR emitter / sensor modules, but never found a suitably small one for a 9mm track guage (N scale)... I never even considered the possibility of simply installing an IR emitter right next to an IR sensor... D'oh! 🤦‍♀️

I suppose the only question for this would be how susceptible would this solution be to the original problem of changing light conditions? My mind says it shouldn't make any difference due to it using IR instead of visible light, but not being a physicist......

But this all seems to be getting very complicated, compared with your original proposal (particularly as refined by hippy to use an average for each sensor). Basically, all you need is a single LDR in the track, connected by one wire to a PICaxe pin running a simple averaging algorithm for each track-location (so no physical "reference" or "calibration" is needed). Two adjacent sensors at any location then could be a refinement to infer the direction of movement, if so required.
Yeah, I'm bad at that - I get shown a rabbit hole, and I just go "ooh - shiny!" and dive down it, forgetting an easier solution which was mentioned earlier...

So what would people suggest would be the best option? The LDR would need some more programming time (which I can live with), while the IR solution would need less programming but more components (easy enough to hide between the rails)... Or perhaps a combination of the two?
 

Hemi345

Senior Member
Maybe something like this Vishay TSSP770 proximity sensor: LINK
Doesn't have to sit in between the tracks. It could be hidden in an object track side, like disguised inside a rail signal or something.
 
Maybe something like this Vishay TSSP770 proximity sensor: LINK
Doesn't have to sit in between the tracks. It could be hidden in an object track side, like disguised inside a rail signal or something.
The problem with lineside is that there's a number of locations where there are two tracks right next to each other - that introduces the possibility of accidentally detecting the train on the other track. Plus, in at least one location that I can think of, there is quite literally nothing on either side of the track - it's an American bridge, so track, deck and nothing else!

Mind you, going by the datasheet, at only 3mm wide I see no reason why I shouldn't be able to fit that between rails... I'll definitely look into that one a bit more! Thank you!
 

AllyCat

Senior Member
Hi,
I suppose the only question for this would be how susceptible would this solution be to the original problem of changing light conditions? My mind says it shouldn't make any difference due to it using IR instead of visible light, but not being a physicist......
Yes, visible and IR light are very similar, but a few materials can be "transparent" to IR and not visible light. Direct sunlight is almost equally balanced between visible and (near) IR (with just a few percent UV). A "disadvantage" of IR is that you can't see it !, which can make setup and testing difficult. However, a useful trick is that many digital cameras (and phones) do "see" IR, so can help with testing. But if this is an "exhibition" layout, then bear in mind that some of the photographs might give away your "secrets".

Personally, I like hippy's single-sensor with averaging method: but calculating a running average (e.g. by adding 10% of the present value to 90% of the previous, averaged, value), needs some care to avoid mathematical "rounding" (truncation) or "overflow" errors. Also bear in mind that a "detection threshold" at say 50% (or 150%) of the average light level will have a very different magnitude if the "reference" ADC value is e.g. 10 (bright) rather than 100 (dim).

If direct sunlight striking the sensor(s) is an issue, then the "Reference Sensor" idea probably won't work anyway (because only one sensor might be in a shadow). Sunlight is extremely bright and may overload (saturate) a sensor, so the only reliable (optical) method probably would be to use modulated light (or IR).

Cheers, Alan.
 

erco

Senior Member
Wow... so much hate...
I admit, I have a low tolerance for people who waste my and others time, when we're trying to help. BTW when you're in a PICAXE-sponsored forum and you claim you're using a Picaxe, it's really bad form to casually mention "I might not even use a Picaxe", especially after so many helpful people replied. Your actions are no better than those of the people who consume hours of a salesman's time in a brick and mortar store to select an item, then go home and order it online to save a few bucks.

You've certainly drained my enthusiasm tanks for a while, in terms of helping people out here. A pity since I probably won't help the next guy who might actually appreciate it. Please consider your actions more thoughtfully in future posts.
 

hippy

Technical Support
Staff member
I don't think anyone should get upset with danners430 as it seems a PICAXE was, and possibly still is, in the running, so I wouldn't consider asking having wasted anyone's time, nor that anyone who had replied had wasted theirs.

I don't believe there was any deceit here, no asking for help with one thing while intending to use something else all along, like asking for solutions to coursework while not declaring that.

I am sure all of us here would like people to choose a PICAXE, will 'sell them the virtues of doing so', but there always are alternatives; sometimes better, simpler, easier, or cheaper. It is sensible to consider all the options.

There is nothing wrong in changing direction and, even if someone does, it doesn't mean they are never coming back again. It might have been a case of "looks great, but not for this particular project", and they may even have a change of heart as they reflect on the options.

The best one can do is take the wins and suck-up those which aren't. Helping as best as one can doesn't always ensure a win, but it can secure wins in the future. And even if not, just helping someone advance their project is a win in itself.

And, if nothing else, any help given remains for everyone else who may need that in the future. And it may even lead people looking at options for their non-PICAXE projects to choose a PICAXE.
 

mikeyBoo

Senior Member
Right on hippy. Can’t remember who said this but it’s good advice:
“Always do what you know is right, regardless of the outcome, ‘cause sometimes people disappoint you.”

My view is that 90% of the time, a Picaxe is the best solution for my little projects, meaning 10% of the time it ain’t.

And since we’re on a British site, here’s a quote I like about dealing with difficult or obnoxious people:
“I learned long ago, never to wrestle with a pig. You get dirty, and besides, the pig likes it.” George Bernard Shaw.

It’s difficult to understand (being raised Christian) that some cultures don’t have empathy or gratitude as part of their psychology.
Thankfully, most “techies” aren’t like that. (scientists, engineers, IT people, hobbyists, etc.)

Ok… back to work on my “Picaxe Time Machine”. At my present rate of progress, I should be done by last Thursday.
 
It was the end of a long week when I wrote that - it was a little sarky, for which I apologise. I'm still unsure of what to use, but yes - PICAXE is very much still "in the running", especially as it's so customisable for my needs on this project... In particular, one major plus is the fact I can set the i2c slave address to anything I wish - which means I can have an arbitrary number of PICAXE devices alongside commercial EEPROMs, I/O expanders, etc etc. without running out of addresses. One of the main design objectives for this system is modularity, so that's a major plus!

In order to remove any confusion (I know, this will probably create more ;) ), this is the acual system topology:

The model railway is constructed of multiple baseboards, designed to be "easily" taken apart and stored or transported. In other words, a minimum of wires/cables between baseboards is advantageous. Therefore, the main design objective is to give each baseboard its own self-contained control logic. For the "central processor", or "logic board" as I'm calling it, I'm planning a Teensy - purely because it has CAN on board, a silly amount of program memory, and native SD card support (dedicated pins).
The various logic board will communicate between one another using the CANBus, as the underside of a model railway is a reasonably noisy place. It's also good for longer distance communication - it won't have any problems whatsoever for the 6m bus on this layout - and message, rather than command, based - if something happens (sensor is set off, button is pressed) that is just broadcast out, and the various logic boards carry out whatever action it's been programmed to do. If multiple boards need to carry out actions, then one "message" just replaced multiple "commands".

Within each baseboard, I'm going to use i2c to communicate between the logic board and the various peripherals - the ADC in this thread being one of them. I'll also have relays, solenoids, button matrices, LED matrices and probably more... They're all designed to be "tacked on" the i2c bus if needed, and left off if not. The SD card on the Teensy would contain the configuration for that particular logic board, with the peripherals and list of actions to undertake for each message.

So yes, the PICAXE is still very much in the running - but for a specific use-case, namely the LDRs. Whether I use it over an I/O expander is unsure - it could be anything, and simply depends on what seems the most sensible... Hey - I may end up including footprints for both on the PCB (populate whichever is most sensible for an application...)
 
Well, I've done the sums, and worked out what makes the most sense... It would appear that using LDRs and a PICAXE is cheaper in the long run than multiple I/O expanders and infrared proximity sensors... primarily because I already have a large stock of LDRs!

To adapt your concept, Hippy, would it make sense to calibrate each individual sensor in varying light conditions prior to use, by shining lights of different intensities at the LDR and running a train over? Then use something similar to your concept to extrapolate those values to the ambient lighting conditions...
 

premelec

Senior Member
To reiterate - if you use 2 LDRs - in series - one looking at ambient and one with trains passing over it automatically calibrates the ratio - so you look for change in the voltage at the junction of the two LDRs....
 

hippy

Technical Support
Staff member
To adapt your concept, Hippy, would it make sense to calibrate each individual sensor in varying light conditions prior to use, by shining lights of different intensities at the LDR and running a train over? Then use something similar to your concept to extrapolate those values to the ambient lighting conditions...
I am not entirely sure how you mean because my code is auto-calibrating and, remembering my AXE091 has an LDR as well as a pot, worked as desired by simply swapping a jumper wire. I also swapped the SERTXD for SOUND and a piezo because that gave better feedback.

The only thing which might need calibrating is the amount of change required to indicate there has been a drop in light level, how many samples are needed, plus of course adjusting to whether you have increasing level with darkness or light. That might depend on how many LDR you are handling, how fast you run the PICAXE at.

All that should however only be an issue while developing the code and there should be no need of calibration during use.
 

AllyCat

Senior Member
Hi,

If the LDRs are coming from your "spares box" then it would be wise to give them a simple "go/nogo" test, for example <10k in bright light and >1M in darkness. Then rely on self-calibrating software as discussed above.

However, if you do decide to use pairs in a balancing/bridge configuration then it would be wise to characterise and match them in pairs (which is why I wouln't bother with that method). :)

Cheers, Alan.
 

hippy

Technical Support
Staff member
If the LDRs are coming from your "spares box" then it would be wise to give them a simple "go/nogo" test, for example <10k in bright light and >1M in darkness. Then rely on self-calibrating software as discussed above.
Good point. If they are being used for ADC then one ideally needs each resistor chosen to match it, to give the widest spread between light and dark. If the spread is too narrow any triggering may become too sensitive.
 
OK, I spent the weekend developing some firmware - it seems to work in the simulator, and simply requires the "master" device to poll it over i2c every so often. Any thoughts on the attached?
 

Attachments

lbenson

Senior Member
Two things.

1) Your extensive use of the "#IF" directive is very unusual practice. What is your intention in doing it this way?

2) Much of the code is repetitive, varying only variables and pin numbers. You could probably combine multiple instances of similar code into a single instance in a loop, perhaps using ptr and bptr or get/put, peek/poke to walk through your variables/pins. (This would be slower, but in many cases that would not make a difference in actual performance.)
 
The reason behind using the directives is (in my mind at least) a simple one - I'm only going to have a certain number of sensors connected at any one time, with multiple installations each with differing numbers. Using the directives allows me to *very* quickly only program the code needed for the number of sensors connected, resulting in a faster overall program flow (no need to sample the unused sensors).

It was just the easiest way I could find to make batch programming as easy as possible - a simple directive at the top to say how many sensors were connected, which could then be altered in a second or so.

For your second point, this again stems from the above desire to only program the code necessary.
With hindsight (what a wonderful thing!) I could have used precisely your suggestion, using the directives instead to determine what the upper limit of the loop counter would be... perhaps a re-write for a future day!
 
(In fact, having a quick scan of the code, it wouldn't even be that hard... as long as my scratchpad entries are always 5 bytes long, it would be a simple case of incrementing two addresses then repeating........)

be right back!!
 
OK, I've changed the Main procedure with the following. I wasn't able to change the init procedure as this uses a set of symbols to set the "default" brightness level, again for ease of programming. But this seems to work...

Code:
Do
    varOffset = var0
    
#IF number = 1
    for i = 0 to 0
#ELSEIF number = 2
    for i = 0 to 1
#ELSEIF number = 3
    for i = 0 to 2
#ELSEIF number = 4
    for i = 0 to 3
#ELSEIF number = 5
    for i = 0 to 4
#ELSEIF number = 6
    for i = 0 to 5
#ELSEIF number = 7
    for i = 0 to 6
#ELSEIF number = 8
    for i = 0 to 7
#ELSEIF number = 9
    for i = 0 to 8
#ELSEIF number = 10
    for i = 0 to 9
#ELSEIF number = 11
    for i = 0 to 10
#ELSEIF number = 12
    for i = 0 to 11
#ELSEIF number = 13
    for i = 0 to 12
#ELSEIF number = 14
    for i = 0 to 13
#ELSEIF number = 15
    for i = 0 to 14
#ELSEIF number = 16
    for i = 0 to 15
#ELSEIF number = 17
    for i = 0 to 16
#ELSEIF number = 18
    for i = 0 to 17
#ELSEIF number = 19
    for i = 0 to 18
#ELSEIF number = 20
    for i = 0 to 19
#ELSEIF number = 21
    for i = 0 to 20
#ELSEIF number = 22
    for i = 0 to 21
#ELSEIF number = 23
    for i = 0 to 22
#ELSEIF number = 24
    for i = 0 to 23
#ELSEIF number = 25
    for i = 0 to 24
#ELSEIF number > 25
    for i = 0 to 25
#ENDIF
    
    select i
    case < 4
        i2 = i
    case <16
        i2 = i + 1
    else
        i2 = i + 2
    end select
    
    readadc i2, ldrreading
    
    call readscratchpad
    call processing
    call writescratchpad
    
    varoffset = varoffset + 5
    
    next i

Loop
}
end
 
Top