Arduino Crossfading Nightlight

This post describes a simple nightlight that turns on when you turn the lights off. It uses a RGB LED for a cool effect.


Of course, you’ll need some wires and a breadboard, but the schematic doesn’t include that. You can make this thing however you wish.


This is how you’ll want to connect your components together.

The reason for the pin choices is that this project relies on PWM and as you can see in the schematic, not all pins support this feature. You can move the photoresistor pin to any analog pin you choose.

NOTE: You’ll want to connect the ground wire of the photoresistor to the GND pin on the analog side, and the LED ground to the GND pin on the digital side. Otherwise, the threshold will be lower (unfortunately, I’m only starting to learn electronics so I can’t explain this).


The code

The variables which are safe to change are the pins, maxPower, and the wait. As shown in the variable definition, maxPower must be between 0 and 255.

Due to the transitions used within the loop, the color will always start at full red. If the starting values are changed, some of them will become negative throughout the loop.

// digital pins
int redPin   = 3;
int greenPin = 5;
int bluePin  = 6;

// analog pins
int photocellPin = A5;

const int maxPower = 255 % 256;
const int threshold = 768;

// Color variables (we'll start with red)
// if you change these, you'll break the transitions in the loop
int redVal   = maxPower;
int greenVal = 0;
int blueVal  = 0;

int i = 0;
int wait = 50; // in milliseconds

void setup()
  pinMode(redPin,   OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin,  OUTPUT);

void loop()
  unsigned int val = analogRead(photocellPin);

  if (val < threshold) {
    analogWrite(redPin,   redVal);
    analogWrite(greenPin, greenVal);
    analogWrite(bluePin,  blueVal);

    if (i < maxPower) { // red -> green
      blueVal = 0;
    } else if (i < maxPower*2) { // green -> blue
      redVal = 0;
    } else { // blue -> red
      greenVal = 0;

    i = (i + 1) % (maxPower*3);

  } else {
    analogWrite(redPin,   0);
    analogWrite(greenPin, 0);
    analogWrite(bluePin,  0);


Hopefully this will help you get started making yourself a cool automatic nightlight. An interesting improvement would be to be able to start at any color (as long as redVal + greenVal + blueVal == 255), but that’s left as an exercise to the reader.

Published on June 01, 2014.