pulseIn() seems to display a strange bug of unstable output when read from two different input pins. I've found a workaround, but it's not very elegant. Here's the problem:
I'm using two TSL230 chips to read two different light sources and I'm using pulseIn() to read them like so:
SENSOR1_duration = pulseIn(FREQ1_PIN, HIGH); // read the first TSL230 chip
SENSOR2_duration = pulseIn(FREQ2_PIN, HIGH); // read the second TSL230 chip
This should give me consistent data from each sensor if the light is not changing, but instead I get a stream of data like this:
S1=30349 S2=20614
S1=19241 S2=2356 <--- note the weird values here from S2
S1=30217 S2=20832
S1=15929 S2=5609
S1=30466 S2=20769
S1=12717 S2=8887 <--- and here from S1 and S2
S1=30639 S2=20939
S1=9767 S2=11907 <--- and here from S1
S1=30455 S2=21000
S1=6613 S2=14913
S1=27073 S2=20935
S1=3819 S2=17583
S1=24214 S2=20877
S1=560 S2=20959
S1=21479 S2=2274
S1=30465 S2=20801
S1=16194 S2=5524
Note the values jittering around.
On the other hand, if I simply read one sensor only (no change in hardware, just commenting out the other pulseIn()), I get steady, consistent output like this:
S1=30407
S1=30284
S1=30443
S1=30467
S1=30492
S1=30597
S1=30681
S1=30746
S1=30569
S1=30477
S1=30594
S1=30964
S1=30474
S1=30847
If I read the other sensor alone, I get similarly stable values. It's only when reading both pulseIn()s that I get the unstable output.
The workaround--which works perfectly--is to read each sensor twice and throw away the first value. Code looks like this:
SENSOR1_duration = pulseIn(FREQ1_PIN, HIGH); // gets thrown away.
SENSOR1_duration = pulseIn(FREQ1_PIN, HIGH); // re-do the pulseIn()
SENSOR2_duration = pulseIn(FREQ2_PIN, HIGH); // gets thrown away.
SENSOR2_duration = pulseIn(FREQ2_PIN, HIGH); //re-do the pulseIn()
This gives the expected output with no jumping around:
S1=30407 S2=20879
S1=30284 S2=21087
S1=30443 S2=20994
S1=30467 S2=20842
S1=30492 S2=20914
S1=30597 S2=20857
S1=30681 S2=20902
S1=30746 S2=20777
S1=30569 S2=20700
S1=30477 S2=20953
S1=30594 S2=20767
S1=30964 S2=20823
S1=30474 S2=20844
S1=30847 S2=20707
S1=30824 S2=20989
S1=30496 S2=20834
S1=30465 S2=20746
S1=31029 S2=20771
I've tried various other ways to work around this weirdness (turning off interrupts, adding delays, etc.), but this is the only way that works, yet it shouldn't be necessary. Am I missing something? Is the arduino team missing something? Is the Wiring code underlying pulseIn() buggy?