Monday, September 12, 2011

stairwell sensor light: Arduino!

So I wanted a small light at the bottom of the short set of stairs that lead from the door of my apartment into the main living area. I've been learning about Arduino lately, so I figured this might be a practical experiment. I decided to use a reed switch to sense when the door had been opened.

After getting frustrated at the reed switch functioning just fine when closed (Arduino digitalRead() returning HIGH) but bouncing around randomly when it should have been staying open, I did some Googling and found that I should have used a pullup resistor to coax the current in the right direction. I don't pretend to understand why this works, but I intend to find out.

Anyway, I used a circuit based very much on this one, plus of course an RGB LED to do the actual lighting. The next step is to grab a couple more RGB LEDs (I only had one on hand that had been supplied in the Sparkfun Inventors Kit) and make it brighter.

Learning about and experimenting with Arduino has been a lot of fun so far. Am working on a larger project for the bike. Along the way I've dramatically improved my soldering skills, though they are still pretty terrible!

#include <Time.h>

// pins
const int reedswitch = 2;
const int red = 9;
const int green = 10;
const int blue = 11;

// door states
const int DOOR_OPEN = 0;
const int DOOR_CLOSED = 1;

// minimum time the courtesy light will stay on for (seconds)
const int MIN_OPENTIME = 10;

///////////////////////////////////////////

int door = DOOR_CLOSED;
int last_open_at = 0;

void setup() {
  pinMode(reedswitch, INPUT);
  setTime(0);
}

void rgbled(int r, int g, int b) {
  analogWrite(red,r);
  analogWrite(green,g);
  analogWrite(blue,b);
}

void loop() {
  int reedswitch_state = digitalRead(reedswitch);
  if (reedswitch_state == HIGH && now() >= last_open_at + MIN_OPENTIME) {
    door = DOOR_CLOSED;
  } else if (reedswitch_state == LOW) {
    last_open_at = now();
    door = DOOR_OPEN;
  } else {
    // no change in state, do nothing
  }
  if (door == DOOR_OPEN) {
    rgbled(255,255,255);
  } else {
    rgbled(0,0,0);
  }
  delay(500);
}

No comments:

Post a Comment