/*
  LED Bar Graph with Photoresistor Sensor
  by Anderson Costa with ❤ for the Wokwi community
  Visit https://wokwi.com to learn about the Wokwi Simulator
*/

// These constants should match the photoresistor's "gamma" and "rl10" attributes
const int sensorPin = A0; // Set pin of the Photoresistor sensor
const float GAMMA = 0.7;
const float RL10 = 50;
const int ledCount = 10;  // Set number of LEDs in the bar graph

// Array of pins for LEDs in the bar graph
int ledPins[] = {
  2, 3, 4, 5, 6, 7, 8, 9, 10, 11
};

void setup() {
  // Loop over the LEDs pins and set all to output
  for (int thisLed = 0; thisLed < ledCount; thisLed++) {
    pinMode(ledPins[thisLed], OUTPUT);
  }
}

void loop() {
  // Read the Photoresistor sensor value
  int sensorReading = analogRead(sensorPin);

  // Convert the analog value into lux value
  float voltage = sensorReading / 1024. * 5;
  float resistance = 2000 * voltage / (1 - voltage / 5);
  float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));

  // Map the result to a range from lux to the number of LEDs
  int ledLevel = map(lux, 0, 1023, 0, ledCount);

  // Loop over the LEDs pins and set element
  for (int thisLed = 0; thisLed < ledCount; thisLed++) {
    // If the array element's index is less than ledLevel
    if (thisLed < ledLevel) {
      // Turn the pin for this element on
      digitalWrite(ledPins[thisLed], HIGH);
    } else {
      // Turn off all pins higher than the ledLevel
      digitalWrite(ledPins[thisLed], LOW);
    }
  }
}