Skip to content

Instantly share code, notes, and snippets.

@jscrane
Created July 21, 2011 13:42
Show Gist options
  • Save jscrane/1097209 to your computer and use it in GitHub Desktop.
Save jscrane/1097209 to your computer and use it in GitHub Desktop.
Arduino sketch for Twilight gadget
#define LIGHT 5
#define MOTION 0
#define SWITCH 1
#define LEDS 2
#define DUSK 4
#define HZ 4
#define SAMPLES (15*HZ)
#define ON_DELAY (30*60*HZ)
#define OFF_DELAY (15*HZ)
#define DARK_THRESHOLD 720
#define LIGHT_THRESHOLD 680
boolean off = true;
int onCount = 0, offCount = 0;
int samples[SAMPLES], pos, smoothed;
long total;
int readLight() {
int reading = analogRead(LIGHT);
return reading;
}
int sampleLight() {
int curr = readLight();
total += curr - samples[pos];
samples[pos++] = curr;
if (pos == SAMPLES) pos = 0;
smoothed = (int)(total / SAMPLES);
return curr;
}
void setup() {
pinMode(MOTION, INPUT);
pinMode(SWITCH, INPUT);
digitalWrite(SWITCH, HIGH); // activate pull-up
pinMode(LEDS, OUTPUT);
pinMode(DUSK, OUTPUT);
smoothed = readLight();
for (int i = 0; i < SAMPLES; i++) {
samples[i] = smoothed;
total += smoothed;
}
}
inline boolean manual() {
return digitalRead(SWITCH) == LOW;
}
inline boolean isDark(int val) {
return val > DARK_THRESHOLD;
}
inline boolean isDark() {
return isDark(smoothed);
}
inline boolean isLight(int val) {
return val < LIGHT_THRESHOLD;
}
inline boolean isLight() {
return isLight(smoothed);
}
void turnOn() {
if (off) {
digitalWrite(LEDS, HIGH);
off = false;
}
}
void turnOff() {
if (!off) {
digitalWrite(LEDS, LOW);
off = true;
}
}
inline boolean movement() {
return digitalRead(MOTION) == HIGH;
}
inline void updateIndication(int val) {
digitalWrite(DUSK, isDark(val) || isLight(val)? HIGH: LOW);
}
void loop() {
updateIndication(sampleLight());
if (manual()) {
if (off) {
turnOn();
onCount = ON_DELAY;
} else {
turnOff();
offCount = OFF_DELAY;
}
} else if (movement()) {
onCount = ON_DELAY;
if (offCount == 0 && isDark())
turnOn();
} else if (onCount == 0)
turnOff();
delay(1000 / HZ);
if (offCount > 0) offCount--;
if (onCount > 0) onCount--;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment