Reverse Photocell code [code example]

Greetings,
I made a reverse photocell code to light the LEDs when it gets dark:

//www.elegoo.com
//2016.12.9
//www.treedbox.com

int lightPin = 0;
int latchPin = 11;
int clockPin = 9;
int dataPin = 12;

int leds = 0;

void setup()
{
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  Serial.begin(9600);
}
void updateShiftRegister()
{
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, LSBFIRST, leds);
  digitalWrite(latchPin, HIGH);
}
void loop()
{
  int reading  = analogRead(lightPin);
  int numLEDSLit = 12 - reading / 10;  //1023 / 9 / 2
  Serial.print("reading: ");
  Serial.print(reading);
  Serial.print(" numLEDSLit: ");
  Serial.println(numLEDSLit);

  if (numLEDSLit > 8) numLEDSLit = 8;
  leds = 0;   // no LEDs lit to start
  for (int i = 0; i < numLEDSLit; i++)
  {
    leds = leds + (1 << i);  // sets the i'th bit
  }
  updateShiftRegister();
}

The cat's leap is here:

int numLEDSLit = 12 - reading / 10;

Where reading / 10 gets a number under 100 when it gets dark and divide by 10. Then take this result (10) and subtract from 12: 100 /10 = 10, 12-10 = 2.

in response, 2 LEDs will light up!

Anything above reading 130 will be negative, reading 120 will be 0.

This code is based on Elegoo that turns on the LEDs when it gets brighter:

//www.elegoo.com
//2016.12.9

int lightPin = 0;
int latchPin = 11;
int clockPin = 9;
int dataPin = 12;

int leds = 0;

void setup() 
{
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);  
  pinMode(clockPin, OUTPUT);
}
void updateShiftRegister()
{
   digitalWrite(latchPin, LOW);
   shiftOut(dataPin, clockPin, LSBFIRST, leds);
   digitalWrite(latchPin, HIGH);
}
void loop() 
{
  int reading  = analogRead(lightPin);
  int numLEDSLit = reading / 57;  //1023 / 9 / 2
  if (numLEDSLit > 8) numLEDSLit = 8;
  leds = 0;   // no LEDs lit to start
  for (int i = 0; i < numLEDSLit; i++)
  {
    leds = leds + (1 << i);  // sets the i'th bit
  }
  updateShiftRegister();
}

Very nice,
But what is exactly your question?
How can the forum help you?

OP posted in the Introductory Tutorials - Arduino Forum section, so might not be a question.

I would not call this a tutorial though, it lacks some explanations of the whole code.

1 Like

Did you mean

const byte  lightPin = A0;
const byte  latchPin = 11;
const byte clockPin = 9;
const byte  dataPin = 12;

?

Why is "updateShiftRegister" not simply inline code?
Then leds wouldn't need global scope

elegoo's code was poor to start with... (not an excuse for not improving it)

Amen!

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.