Skip to content

Instantly share code, notes, and snippets.

@mtantawy
Created March 23, 2016 21:32
Show Gist options
  • Select an option

  • Save mtantawy/aa37f6f7ee9144e4cc33 to your computer and use it in GitHub Desktop.

Select an option

Save mtantawy/aa37f6f7ee9144e4cc33 to your computer and use it in GitHub Desktop.
Arduino sketch to control LEDs based on a light sensor, light up the LEDs when the light is low and vice versa.
int photoRPin = 0;
int minLight; //Used to calibrate the readings
int maxLight; //Used to calibrate the readings
int lightLevel;
int adjustedLightLevel;
void setup() {
//Serial.begin(9600);
//Setup the starting light level limits
lightLevel=analogRead(photoRPin);
minLight=lightLevel-20;
maxLight=lightLevel;
// LEDS
for (int thisPin = 1; thisPin <= 10; thisPin++) {
pinMode(thisPin, OUTPUT);
}
}
void loop(){
//auto-adjust the minimum and maximum limits in real time
lightLevel=analogRead(photoRPin);
if(minLight>lightLevel){
minLight=lightLevel;
}
if(maxLight<lightLevel){
maxLight=lightLevel;
}
//Adjust the light level to produce a result between 0 and 10
adjustedLightLevel = map(lightLevel, minLight, maxLight, 0, 10);
//Send the adjusted Light level result to Serial port (processing)
//Serial.println(adjustedLightLevel);
//Serial.println(lightLevel);
// LEDS
// shutoff all LEDs first
for (int thisPin = 1; thisPin <= 10; thisPin++) {
digitalWrite(thisPin, LOW);
}
// then light up only as needed
int needed = 10 - adjustedLightLevel;
for (int thisPin = 1; thisPin <= needed; thisPin++) {
digitalWrite(thisPin, HIGH);
}
//slow down the transmission for effective Serial communication.
delay(500);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment