const int LIGHT_SENSOR_PIN = A0; // Arduino pin connected to light sensor's pin
const int RELAY_PIN = 3; // Arduino pin connected to Relay's pin
const int ANALOG_THRESHOLD = 80;
const int MOTION_SENSOR_PIN = 7;
int motionStateCurrent = LOW; // current state of motion sensor's pin
int motionStatePrevious = LOW; // previous state of motion sensor's pin
// variables will change:
int analogValue;
void setup() {
Serial.begin(9600);
pinMode(MOTION_SENSOR_PIN, INPUT); // set arduino pin to input mode
pinMode(RELAY_PIN, OUTPUT); // set arduino pin to output mode
}
void loop() {
motionStatePrevious = motionStateCurrent; // store old state
motionStateCurrent = digitalRead(MOTION_SENSOR_PIN); // read new state
analogValue = analogRead(LIGHT_SENSOR_PIN); // read the input on analog pin
The loop function goes round about a million times a second. If MOTION_SENSOR_PIN goes high your code will make RELAY_PIN high. A millionth of a second later it will go low. A relay cannot respond that fast. Put some serial.prints in your code to see what is happening, study the state change and doing several things at the same time tutorials.
Analyze this "if":
if (analogValue < ANALOG_THRESHOLD && motionStatePrevious == LOW && motionStateCurrent == HIGH) {
MotionStatePrevious and motionStateCurrent are always in the same condition, either both HIGH or both LOW.
See in the simulator.
In the simulator I added a delay to preview the print.
I used an LDR as a LIGHT sensor and a PIR as a presence sensor.
Adjust LDR for more 3,500 LUX and simulate motion on PIR
Are you sure? Maybe I am misreading, but as I see it if MOTION_SENSOR_PIN goes high then motionStateCurrent will also go high but motionStatePrevious will remain low until the next iteration of the loop function, giving the possibility of the if statement being true for one iteration of the loop function, assuming that analogValue is less than ANALOG_THRESHOLD. However, as per my previous reply, this is only the case for about 1 millionth of a second, or however long the loop function takes to go round once.
@PerryBebbington is right.
I redid the simulator, I put a delay in the simulator, leaving only the printout of the activated relay.
See again in the simulator above.