Thursday, November 10, 2011

InduinoX and wireless relays: Part II

In my last post, I played a bit with the wireless relays to turn on a light. In this post I will show how to use LDR to detect when to turn on the light depending on the ambient light.

Lets dive into the code quickly

#define TRUE  1
#define FALSE 0

int LIGHT_PIN = 7;
int SLEEP_TIME = 100;
int LDR_PIN = 3;
int LDR_THRESHOLD_FOR_DARK = 350;
int MAX_COUNT_BEFORE_TOGGLE = 10;

int isLightOn = FALSE;
int toggleCount = 0;

void setup() {
  turnOffDevice(LIGHT_PIN);
  digitalWrite(LIGHT_PIN, LOW);

  Serial.begin(115200);
}

void turnOffDevice(int pin) {
  pinMode(pin, INPUT);
}

void turnOnDevice(int pin) {
  pinMode(pin, OUTPUT);
}

void toggleLight() {
  if (isLightOn) {
    turnOffDevice(LIGHT_PIN);
    isLightOn = FALSE;
  } else {
    turnOnDevice(LIGHT_PIN);
    isLightOn = TRUE;
  }
}

void toggleLightIfNecessary(int input, int threshold) {
  if (input > threshold) {
    toggleCount++;
    if (toggleCount > MAX_COUNT_BEFORE_TOGGLE) {
      toggleLight();
      toggleCount = 0;
    }
  } else {
    toggleCount = 0;
  }
}

void loop()
{
  delay(SLEEP_TIME);
  int ldrReading = 1023 - analogRead(LDR_PIN);
  Serial.println(ldrReading);

  Serial.println(toggleCount);
  if (isLightOn) {
    toggleLightIfNecessary(ldrReading, LDR_THRESHOLD_FOR_DARK);
  } else {
    toggleLightIfNecessary(1023 - ldrReading,
                           1023 - LDR_THRESHOLD_FOR_DARK);
  }
}

So in the loop(), I keep reading the data from the light sensor, invert it and check to see if the light is already turned on. If it is already on and there is enough ambient light, then I turn in off. If the light is off, then it is turned on if the ambient light is not sufficient.

In both cases, I make sure the sensor data is consistently above or below the threshold. Otherwise the light might turn on when some one's shadow causes the light sensor to report a low light etc.

Some things to note:
  1. In this experiment, I made sure that the light sensor is pointed away from the light source and towards a window from where sun light comes into the room.
  2. The threshold value is empirical, based on conditions in my room and my "feeling" of darkness.