ATtiny85: night light with button and sleep
Fades on in the dark, sleeps at microamps in daylight.
- ATtiny85
Open in the simulatorNo account needed: press Simulate and it runs.
How it works
An ATtiny85 on a 3 V battery: the light sensor RV1 (LDR to GND, R1 10 kΩ to VCC) on A3 (PB3) tells how dark it is. Below about 10 lx the LED on PB0 fades up (PWM from Timer0), above it fades down. Button SW1 on PB2 switches auto / always on / off (pin-change interrupt). While the LED is off the chip sleeps in power-down and the watchdog wakes it every 250 ms: watch the supply current drop to microamps. Change the illuminance of the LDR in the inspector during the run.
Wiring
Each line is one connection (net) and the pins it joins.
| Net | Pins |
|---|---|
| GND | BT1 −C1 2D1 KRV1 2SW1 2U1 GND |
| VCC | BT1 +C1 1R1 1U1 VCC |
| BTN | SW1 1U1 PB2 SCL SCK A1 |
| LED | R2 1U1 PB0 ~ SDA MOSI |
| LED_A | D1 AR2 2 |
| SENSE | R1 2RV1 1U1 PB3 A3 |
- D1
- LED
- R1
- Resistor
- R2
- Resistor
- SW1
- Push button
Parts
Firmware
sketch.ino · 47 lines
// ATtiny85 night light
// - A3 (PB3): light sensor, an LDR to GND and 10 kΩ to VCC: the darker, the higher the voltage
// - PB0: LED (PWM, Timer0); it fades up when it gets dark and down when it gets light
// - PB2: button to GND: auto -> always on -> off -> auto (pin-change interrupt)
// While the LED is off the chip sleeps (power-down) and the watchdog wakes it every 250 ms to
// look at the light again: the supply current drops from milliamps to microamps.
#include <avr/sleep.h>
#include <avr/wdt.h>
const byte LED = 0, BUTTON = 2, SENSOR = A3;
byte mode = 0; // 0 auto, 1 always on, 2 off
int level = 0; // LED brightness 0..255
volatile bool pressed = false;
ISR(PCINT0_vect) { if (!(PINB & _BV(PB2))) pressed = true; }
ISR(WDT_vect) {}
void setup() {
pinMode(LED, OUTPUT);
pinMode(BUTTON, INPUT_PULLUP);
GIMSK |= _BV(PCIE); // pin-change interrupt on PB2
PCMSK |= _BV(PCINT2);
sei();
}
void sleep250ms() {
wdt_reset();
WDTCR = _BV(WDCE) | _BV(WDE);
WDTCR = _BV(WDIE) | _BV(WDP2); // watchdog interrupt after 250 ms
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
sleep_cpu(); // wakes on the watchdog or the button
sleep_disable();
WDTCR = _BV(WDCE) | _BV(WDE);
WDTCR = 0; // watchdog off
}
void loop() {
if (pressed) { delay(30); pressed = false; mode = (mode + 1) % 3; }
bool dark = analogRead(SENSOR) > 600;
int target = (mode == 1 || (mode == 0 && dark)) ? 255 : 0;
if (level < target) level++;
else if (level > target) level--;
analogWrite(LED, level);
if (level == 0 && target == 0) { digitalWrite(LED, LOW); sleep250ms(); }
else delay(8); // a full fade takes about 2 s
}Open in the simulator