Measuring brightness

Our eyes are unreliable. If you’re anything like me, you’re always frustrated at how our eyes don’t measure brightness linearly. No? Just Me? Sunlight is on average 20 times as bright as indoor lighting and we definitely don’t notice that much of a difference. Anyways, moving on, I wanted to make something that will measure the brightness and give an easy visual indicator to the brightness level currently in the room (and won’t lie to us like our eyes do). So I did this:

The values read from the Light Dependent Resistor are from 0-1024, so what I did is divide the reading by a 100, and store that number in an int variable. What this did is that it extracted the most significant (leftmost) digit of the reading ex: extracts the 7 out of 721. Then, in a for loop, I would set the pins from 0 to the extracted number to high, which resulted in what was shown in the video.

code:

int beginPin = 2;
int endPin = 11;
int sensorPin = A0;

void setup() {
  // put your setup code here, to run once:
  // for loop to set all the pins to output so I don't have to do it manually
    for (int i = beginPin; i <= endPin; i++) {
      pinMode(i, OUTPUT);
    }
    Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
   int sensorReading = analogRead(sensorPin);
   // extracts the leftmost digit of a 3 digit number
   int leds = sensorReading/100;
   Serial.print(sensorReading);
   Serial.print("||");
   Serial.println(leds);
   // for loop to turn off all the leds before setting the relevant ones to high
   for (int i = beginPin; i <= endPin; i++){
    digitalWrite(i,LOW);
   }
   for (int i = beginPin; i < (beginPin+leds); i++){
    digitalWrite(i, HIGH);
   }
}

Oh also as an added bonus, it can also display the brightness as an 8-bit binary number (0-255)

code for the binary display:

int beginPin = 2;
int endPin = 11;
int sensorPin = A0;

void setup() {
  // put your setup code here, to run once:
  for (int i = beginPin; i <= endPin; i++) {
    pinMode(i, OUTPUT);
  }
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  int sensorReading = analogRead(sensorPin);
  byte x = map(sensorReading, 0, 1024, 0, 255);
  Serial.print(x);
  Serial.print(" : ");
  for (int i = 0; i < 8; i++) {
    digitalWrite(i + beginPin, bitRead(x, i));
    Serial.print(bitRead(x, i));
  }
  Serial.println();
}

keep in mind that on the serial monitor this will print the binary number in reverse.

Leave a Reply

Your email address will not be published. Required fields are marked *