I posted this in the Adafruit forums but received no answer there. Start with this MakeCode program:
The simulator console shows that as light intensity
is varied using the upper-left control, the ambient color value
Eventually all 5 possible color values can be seen: 16711680 = 0xff0000 = red; 65280 = 0x00ff00 = green; 255 = 0x0000ff = blue; 16776960 = 0xffff00 = yellow; 16777215 = 0xffffff = white. But the color value seems to change randomly. Is the ambient color value really random, or is there some way to make the simulator simulate each of the 5 possible values in a controlled way?
This has to do with how it works on the hardware. Basically, the process is this:
- The device lights up the LED closest to the light sensor with the color red
- The light from that LED travels to the surface you’re trying to detect the color of and some of it is absorbed by the surface (e.g. if the surface is red, then only the red component of the light will be reflected and the rest is absorbed)
- The light sensor on the device then measures the intensity of light that was bounced back
- Steps 1-3 are then repeated for blue and green.
Once we have measurements for the three colors (red, blue, and green) we can figure out what the surface color is based off the numbers we received. For example, if red is higher than the other colors, then the color of the surface must lean more towards red.
When you run this code in the simulator, it’s going through the same process: “lighting up” the LED with each color and taking readings. The only difference is that when it goes to read the light sensor, the number it gets is based off of the number you input in the simulator rather than any actual reading. That’s why changing the value affects the color output, if you were to have it high when it’s checking red and low when it’s checking green and blue, the function should return that the color is red.
Thank you richard for explaining what is happening and it answers my questions – Is the ambient color value really random? No. Is there some way to make the simulator simulate each of the 5 possible values in a controlled way? No. I tried slewing the intensity up, down, and around as ambient color was measured but failed to be able to get a consistent color return value. I could have used a 1-of-5 choice in the simulator for this (similar to how other sensors are simulated) several weeks ago when working on a related program, but at least now I know it isn’t available. Thanks again for explaining what is happening.