deckle studioIm Editor öffnen

ATtiny85: Nachtlicht mit Taster und Schlafmodus

Blendet im Dunkeln auf, schläft bei Tageslicht mit Mikroampere.

  • ATtiny85
Im Simulator öffnenOhne Konto: Simulieren drücken, und es läuft.

So funktioniert es

Ein ATtiny85 an einer 3-V-Batterie: Der Lichtsensor RV1 (LDR nach GND, R1 10 kΩ nach VCC) an A3 (PB3) misst, wie dunkel es ist. Unter etwa 10 lx blendet die LED an PB0 auf (PWM von Timer0), darüber wieder ab. Taster SW1 an PB2 schaltet Automatik / immer an / aus (Pin-Change-Interrupt). Solange die LED aus ist, schläft der Chip im Power-down und der Watchdog weckt ihn alle 250 ms: Sieh zu, wie der Versorgungsstrom auf Mikroampere fällt. Ändere die Beleuchtungsstärke des LDR im Inspektor während der Simulation.

Verdrahtung

Jede Zeile ist eine Verbindung (Netz) mit den Pins, die sie verbindet.

NetzPins
GNDBT1 −C1 2D1 KRV1 2SW1 2U1 GND
VCCBT1 +C1 1R1 1U1 VCC
BTNSW1 1U1 PB2 SCL SCK A1
LEDR2 1U1 PB0 ~ SDA MOSI
LED_AD1 AR2 2
SENSER1 2RV1 1U1 PB3 A3
D1
LED

Bauteile

Firmware

sketch.ino · 47 Zeilen

// 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
}
Im Simulator öffnen

Weitere Beispiele: Arduino