Motion night light (PIR on 12, RGB on 5, 6 and 9), on an Arduino Uno
An HC-SR501 on pin 12 turns on an RGB LED (red 5, green 6, blue 9) when someone moves, keeps it on for 20 seconds, and checks again before it goes dark. The whole build, an Arduino Uno and 5 more parts, runs here in your browser on the firmware below; open it in the editor to change the wiring or the code and run it again.
Teaching? Assign it to your class in one click.
Beginner Runs in your browser. Free, and no account needed.
The code
The firmware exactly as the editor opens it. Change a line there and press Run: it compiles in the browser.
// A night light that comes on when someone walks past.
//
// HC-SR501 OUT -> pin 12 VCC -> 5V GND -> GND
// RGB LED red -> pin 5, green -> pin 6, blue -> pin 9, each through 220 ohm
// the RGB LED's common cathode -> GND
//
// The HC-SR501 sees the warmth of a moving body. Its output goes HIGH when it
// sees movement and stays high for a few seconds after. The sketch lights the
// LED a warm white, waits 20 seconds, and only turns it off if nothing has
// moved in that time.
//
// Click the sensor's dome to walk past it.
const int PIR = 12;
const int RED_PIN = 5;
const int GREEN_PIN = 6;
const int BLUE_PIN = 9;
const unsigned long ON_MS = 20000;
bool lit = false;
unsigned long litAt = 0;
void color(int r, int g, int b) {
analogWrite(RED_PIN, r);
analogWrite(GREEN_PIN, g);
analogWrite(BLUE_PIN, b);
}
void setup() {
pinMode(PIR, INPUT);
pinMode(RED_PIN, OUTPUT);
pinMode(GREEN_PIN, OUTPUT);
pinMode(BLUE_PIN, OUTPUT);
color(0, 0, 0);
Serial.begin(9600);
Serial.println("Mokxi Uno: motion night light");
}
void loop() {
bool moving = digitalRead(PIR) == HIGH;
if (moving && !lit) {
lit = true;
litAt = millis();
color(255, 180, 90);
Serial.println("someone moved: light on");
} else if (lit && millis() - litAt >= ON_MS) {
if (moving) {
litAt = millis();
Serial.println("still moving: staying on");
} else {
lit = false;
color(0, 0, 0);
Serial.println("nobody there: light off");
}
}
delay(50);
}
Parts list
7 parts, plus the jumper wires. Every one is in the editor's parts bin.
- 1 × Arduino Uno R3
- 1 × Full-size breadboard
- 1 × RGB LED
- 3 × Resistor, 220 Ω
- 1 × Motion sensor
How it is wired
9 connections, pin by pin, read from the circuit itself. Each line is one set of pins joined together, by a jumper wire or a breadboard strip.
- Arduino Uno R3 pin 12; Motion sensor pin OUT
- Arduino Uno R3 pin 9; Resistor, 220 Ω (1) pin 1
- Arduino Uno R3 pin 6; Resistor, 220 Ω (2) pin 1
- Arduino Uno R3 pin 5; Resistor, 220 Ω (3) pin 1
- Arduino Uno R3 pin 5V; Motion sensor pin VCC
- Ground: Arduino Uno R3 pin GND; RGB LED pin C; Motion sensor pin GND
- RGB LED pin R; Resistor, 220 Ω (3) pin 2
- RGB LED pin G; Resistor, 220 Ω (2) pin 2
- RGB LED pin B; Resistor, 220 Ω (1) pin 2
Change it and keep it
Open it in the editor, change the circuit or the code, and keep your version in a free account.