Hello Arduino forum.
I'm new to Arduino so please bear with me if I miss out on something.
I'm trying to write some code that will use an E18-D80NK IR switch sensor to detect when my door opens, turns on an LED which then can only be turned off by a pushbutton when I leave.
I have build my code up from a pushbutton example which can remember the state of the pushbutton, but I have a problem with "disabling" the IR sensor so the code only responds to the pushbutton. I don't know if it is even possible to do so. The IR sensor should be made active again when the pushbutton is off.
I'm using the very basics of programming but wanted to play around with a new kind of input and the IR was available to me. I can't seem to figure out how to remember two input states and shift between which one is prioritised. I have thought about maybe using "switch" or "while" statements but I haven't used them before.
The code as it is now will also blink three times before remembering the state which I think is because of the three "if" statements. Please correct me if I'm wrong, I'm here to learn
This is my code:
const int LED = 13; // LED anode connected to digital pin 13
const int SENSOR = 2; // Infrared proximity switch connected to digital pin 2
const int BUTTON = 7; // Pushbutton is connected to pin 7
int sen_val = 0; // This variable will read the value from the IR sensor
int but_val = 0; // This variable will read the value from the pushbutton
int old_sen_val = 0; // This variable stores the previous value of "sen_val"
int old_but_val = 0; // This variable stores the previous value of "but_val"
int state = 0; // This variable changes if LED is on (=1) or off (=0)
void setup() {
pinMode(LED, OUTPUT); // Defining the LED as an output
pinMode(SENSOR, INPUT); // Defining the infrared sensor as an input
pinMode(BUTTON, INPUT); // Defining the pushbutton as an input
}
void loop() {
sen_val = digitalRead(SENSOR); // Read input value from IR sensor
but_val = digitalRead(BUTTON); // Read input value from pushbutton
// check if there was a transition
if ((but_val == HIGH) && (old_but_val == LOW)) {
state = 1 - state;
delay(100);
}
old_but_val = but_val; // but_val is now old, let's store it
// check if IR sensor detected any movement
if ((sen_val == LOW) && (old_but_val == LOW)) {
state = 1 - state;
}
if (state == 1) {
digitalWrite(LED, HIGH); // turn LED on
} else {
digitalWrite(LED, LOW); // turn LED off
}
}