23 December 2014

Nativity scene light effects with Arduino - the code

And here is the code of my simple light effects. As shown in the previous post I used an Arduino-compatible board called "Pro Micro", compatible with "Leonardo". But any other variant will do.



/*
 Nativity scene lights

 This code controls two LEDs used to animate a Nativity scene.
 A normal LED connected at lampPin goes off during the simulated day.
 A high power LED (use an appropriate driver out of sunPin) simulates
 daylight, including sunrise and sunset fading.

 The circuit:
 * 5mm LED attached lampPin through a 1k resistor and 5V
 * high powered LED driven with an IRF510-like out of sunPin. It
   connects to Vcc through a limiting resistor (do your math and
   take heat dissipation into account).

 Created 20 Dec 2014
 By Paolo Cravero IK1ZYW

 Based on the official Arduino example "Fading":
 http://arduino.cc/en/Tutorial/Fading

 This code is in the public domain.

 */


int sunPin = 3;  
int lampPin = 9;

void setup()  { 
  pinMode(lampPin, OUTPUT);
  digitalWrite(lampPin, LOW);
} 

void loop()  { 
  // fade in from min to max in increments of 1 point:
  for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=1) { 
    // sets the value (range from 0 to 255):
    analogWrite(sunPin, fadeValue);         
    // wait for 50 milliseconds to see the dimming effect
    // adjust to your taste
    delay(50);                            
    // lampPin trigger is at 50
    if (fadeValue > 50) {    
      digitalWrite(lampPin, HIGH);
    }

  } 
  
  // duration of the day, 20 seconds
  delay(10000);
  delay(10000);
  
  // fade out from max to min in increments of 1 point:
  for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=1) { 
    // sets the value (range from 0 to 255):
    analogWrite(sunPin, fadeValue);         
    // wait for 50 milliseconds to see the dimming effect    
    // adjust to your taste
    delay(50);                    
    // lampPin trigger is at 50. Feel free to have hysteresis
    if (fadeValue < 50) {    
      digitalWrite(lampPin, LOW);
    }
  } 

  // duration of the night, 20 seconds
  delay(10000);
  delay(10000);
}