mBlock for Arduino Mega project (2) light sensor project

Youth Innovation Lab
3 min readJan 30, 2020

--

After the first very simple Arduino Mega project — blink LED on Mega board, we can continue to build another relatively simple project, this time, we will use the light sensor, and change LED (pin 13 board) based on the environment brightness.

Before we start our light sensor project, we will try it at the Arduino IDE first, it is the typical proof of concept step, so we know how to create the right project with the right result.

int delayVal = 500;
int debug_values = 1;
int thresholdVal = 800;
int LEDPIN = 13;

void aboveThresh(int value) {
digitalWrite(LEDPIN, HIGH);
}

void belowThresh(int value) {
digitalWrite(LEDPIN, LOW);
}

void setup() {
pinMode(13, OUTPUT);
Serial.begin(9600); //Open serial connection
Serial.println(“Read the light sensor reading …”);
}

void loop() {
int sensorVal = analogRead(A0);

if (sensorVal >= thresholdVal) {
aboveThresh(sensorVal);
}

if (sensorVal < thresholdVal) {
belowThresh(sensorVal);
}

if (debug_values) {
Serial.print(“Sensor value: “);
Serial.println(sensorVal);
}

delay(delayVal);
}

This code is very straightforward, in setup(), initialize the digital pin as an output mode, and open serial port connection (for debugging), then in loop(), read the light sensor value, turn the LED on (HIGH is the voltage level) if the value above the threshold (predefined) , or turn the LED off by making the voltage LOW if the value below the threshold (predefined).

Remember to set the right board (Arduino Mega) and port (port 10 in my test case), then choose “upload” (under Sketch menu), you can start to observe the result, the blink LED on board.

Remember to start the Serial Monitor (from “Tools” menu), and observe the change of the light sensor reading.

Now, it is the time to turn this Arduino project into a mBlock project.

Step 1: start mBlock 5, under “Devices”, click “+”, and choose the right device (Arduino Mega for our project), click “OK”.

step 2: hook Arduino Mega (or UNO) board to one of your USB interface, choose “Upload mode” on, and click “connect” to connect the Mega board.

Hint: remember to choose the right port (for multiple ports)

step 3: from category, choose the right category, then start to drag and drop the blocks, build the project, and save it in your computer (I prefer to save it on local computer, you can choose to save it on cloud only, that is up to you).

Now, it is the time to test it, it may be the simplest project we can build using mBlock for Arduino Mega board, and no need any extra sensors, give it a try.

Please add your comments or suggestions, we will post more tutorials soon.

--

--

Youth Innovation Lab
Youth Innovation Lab

Written by Youth Innovation Lab

Youth Innovation Lab is community based STEM education institute, we promote STEM education to minority community, and focus on advanced technology education.

No responses yet