Greetings all,
I’m trying to adjust this coding for a motion activated light switch in order to accomplish an extra function: I need there to be nothing happening when LDR_PIN is HIGH. If it’s LOW, then I need it to execute the loop as shown. LDR_PIN is connected to an ambient light sensor, so the lights connected through RELAY_PIN don’t need to come on when it’s detecting strong enough light.
Can anyone tell me what additions I need to make and where to make them?
#define PIR0_PIN 0
#define PIR1_PIN 1
#define RELAY_PIN 2
#define LDR_PIN 3
#define TLED_PIN 4
void setup() {
pinMode(PIR0_PIN, INPUT);
pinMode(PIR1_PIN, INPUT);
pinMode(LDR_PIN, INPUT);
pinMode(RELAY_PIN, OUTPUT);
pinMode(TLED_PIN, OUTPUT);
}
void loop() {
if (digitalRead(PIR0_PIN) == HIGH or digitalRead(PIR1_PIN) == HIGH) {
digitalWrite(RELAY_PIN, HIGH);
digitalWrite(TLED_PIN, HIGH);
delay(5000);
digitalWrite(RELAY_PIN, LOW);
digitalWrite(TLED_PIN, LOW);
}
}
I’m lousy at programming, so any guidance is appreciated.
Thanks!
alto777
February 17, 2026, 2:52am
2
I'm sure it can't be this easy
void loop() {
if (digitalRead(LDR_PIN) == HIGH)) return; // skip out on the rest of the loop
if (digitalRead(PIR0_PIN) == HIGH or digitalRead(PIR1_PIN) == HIGH) {
//... what you do now
a7
xfpd
February 17, 2026, 4:52am
3
void loop() {
while (LDR_PIN) {}; // stay on this line and do nothing while LDR_PIN is HIGH
// the rest of the code
}
Is that the exact formatting? Do I need to add “==HIGH” or anything?
xfpd
February 17, 2026, 3:56pm
5
What I posted is one format. You can also use what you mention...
warning, bad coding here. See post #9
void loop() {
while (LDR_PIN == HIGH) {}; // stay on this line and do nothing while LDR_PIN is HIGH
// the rest of the code
}
tigger
February 17, 2026, 4:09pm
6
One is shorthand, and works.
The other is clearer and works as well.
hammy
February 17, 2026, 7:50pm
7
How is your LDR wired ?
is a module with a digital output or a bare sensor its own ( which needs a series resistor and an analog read ) ?
I’m using the DIYables LDR Light Sensor Module . It has a DO output and it’s adjustable to various thresholds.
alto777
February 17, 2026, 9:05pm
9
You need to read the pin, not just test the pin number.
@xfpd was going for a solution essentially identical to the one @alto777 posted, just a different logic to the same effect.
a7
1 Like
hammy
February 18, 2026, 2:26pm
10
With a digital output look in the ide examples about digital inputs . You may need a pull up or pull down resistor .
Write your self a simple sketch to red the LDR and adjust it to give the response you want - bear in mind LDR’s are not fast responding
Read this