Whatever language you use to measure the light level, the program will follow the same basic pattern. The voltage will be read at pin 2 and then scaled to produce a number between 0 and 9 to be displayed on the micro:bit's LED display.
JavaScript Block Code
The JavaScript Blocks Code editor is embedded directly on this page below. From the editor, you can click on Download button (bottom right) and then copy the downloaded file onto your micro:bit. Alternatively, you can Click here to open the editor in a separate browser tab.
The result of the analog read pin block will be a number between 0 and 1023 where 0 represents 0V and 1023 represents 3V. This value is stored in the variable reading. This is then scaled to be a single digit number by dividing by 50. You can change the number 50 to make the light readings more or less sensitive depending on the range of light you are interested in. For instance the light level indoors is considerably less then outdoors on a sunny day.
MicroPython
To run the MicroPython version of the code, open up the online Python editor here and paste the following code into the editor window.
from microbit import * while True: reading = pin2.read_analog() number = int(reading / 50) display.show(str(number))
So that the display only shows a single digit, the number is converted to the integer part of the number (no decimal point) using the int function.
The str function must then be used inside the show method, to convert the integer value into the string that show expects.
Arduino
Make sure that you have your Arduino environment set up for micro:bit by following this guide.
Now start a new Sketch by clicking on the File menu and New. Then paste the following code into the editor window.
#include <Adafruit_Microbit.h> const int readingPin = 2; Adafruit_Microbit_Matrix microbit; void setup() { microbit.begin(); } void loop() { int reading = analogRead(readingPin); int number = reading / 50; microbit.print(number); }
Text editor powered by tinymce.