Light Meter
Part of the Inputs section of Coddy's Arduino journey. Lesson 22 of 22.
This lesson puts the section together: a light meter that prints the light as a percent and shows it on a bar of three LEDs, like the signal bars on a phone.
Split the job into functions, each with one task, so loop() reads like a description:
void loop() {
int percent = lightPercent();
showLevel(percent);
// print the percent
}lightPercent() reads the light module's AO and returns 0 (dark) to 100 (bright). AO falls as the light rises, so map it backwards: map(reading, 0, 1023, 100, 0) turns 1023 into 0 and 0 into 100.
showLevel(int percent) gives each LED of the bar its own threshold: the first lights above 25, the second above 50, the third above 75. Each one needs its else, so the bar can shrink again when the light fades.
Challenge
MediumThe light module's AO is on A0, and the bar's LEDs are on pins 10, 11 and 12:
int lightPercent(): 0 in the dark, 100 in bright lightvoid showLevel(int percent): pin 10 lights above 25, pin 11 above 50, pin 12 above 75- in
loop(), call both, print the percent and wait 200 ms
Press Run, move the light slider, then Check.
Try it yourself
const int lowPin = 10;
const int midPin = 11;
const int highPin = 12;
// write int lightPercent() here
// write void showLevel(int percent) here
void setup() {
pinMode(lowPin, OUTPUT);
pinMode(midPin, OUTPUT);
pinMode(highPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
// read the light as a percent, show it on the bar, print it, wait 200 ms
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Inputs
Practice on your own: Arduino playground