Using MakeCode to read the light sensor is just as easy as previously reading the switches.

The code above is a bit longer to ensure it can is easy to understand. A variable called light gets the value of the sensor from the INPUT group light level block value. The value that the light level block returns is 0 to 255 (which is different than in CircuitPython).

The code will use the NeoPixel LEDs as the indicator. There are ten LEDs, numbered 0 to 9. The map block is used to take the value of light and change it from 0-255 to 0-9. Then that pixel is displayed red. 

The code will pause 0.1 seconds (100 milliseconds), then clear the NeoPixel and start again, forever.

The map in the example uses 245 instead of 255. My flashlight could not get the 10th NeoPixel to light under bright light so I lowered the value. Feel free to raise or lower the values to get the light range you want.

Using Light as a Trigger

There are additional blocks in MakeCode to have code run based on whether the light is below a dark threshold or above a light threshold. Use the set .. light threshold to block from the INPUT group at the start of your code for both light and dark.

With those set you can use the on light bright and on light dark to perform any action you want when the light gets bright or dark.

The example code below sets a NeoPixel green when dark, red when light. NeoPixel 6 is furthest away from the light sensor so readings would not be affected by the indicator.

You can set the thresholds to values that work in your project. 

This guide was first published on Jul 26, 2018. It was last updated on Mar 29, 2024.

This page (MakeCode) was last updated on Mar 08, 2024.

Text editor powered by tinymce.