/* irSwitch This program reads an infrared detector and controls a relay on/off when an object is present near the IR sensor. Parts of this code were inspire by examples in "Getting Started with Arduino" By Massimo Banzi (Make:Books / O'Reilly Media, 2009) Licensed under Creative Commons (BY-NC-SA). */ //set variables int switchPin = 3; int irPin = A0; int irVal = 0; int state = 0; int lastVal = 0; void setup() { Serial.begin(9600); //this is only necessary for troubleshooting or code tweaking. analogWrite(switchPin, 0); } void loop() { irVal = analogRead(irPin); //set val to IR value // if the currtent value is below x, but it was previously higher than x: if ((irVal <= 850) && (lastVal >= 850)) { state = 1 - state; // toggle state } //energize relay if (state == 1) { analogWrite(switchPin, 255); Serial.print("ON: "); Serial.println(irVal); Serial.println(state); } //de-energize relay if (state == 0) { analogWrite(switchPin, 0); Serial.print("OFF: "); Serial.println(irVal); } lastVal = irVal; // update last value to current value delay(300); // pause briefly so light flickers don't cause false triggers (like light between open fingers) /* test code- this prints info to the serial monitor during setup/testing. int sensor = analogRead(A0); // Serial.println(sensor); // delay(250); //digitalWrite(3, HIGH); analogWrite(3, 255); Serial.println("ON"); delay(1000); //digitalWrite(3, LOW); analogWrite(3, 0); Serial.println("OFF"); delay(2000); */ }