Hi,
I'm still new to arduino, I want to turn on ledRed when the ldrStatus goes below 900 but I want it to stay on until I press the button when at that point the ledRed will turn off and ledGreen will come on.
With the ledGreen I want that to go be on when ldrStatus is above 900 and ledRed to be off.
What's the best way to do this?
Thanks
const int ldr = A0; //ldr pin A0
const int ledRed = 13; //red Led pin 13
const int ledGreen = 12; //green Led pin 12
const int pushButton = 2; //pushButton in pin 2
int buttonState = 0; //variable for reading pushButton Status
void setup() {
Serial.begin(9600);
pinMode(ldr, INPUT);
pinMode(ledRed, OUTPUT);
pinMode(ledGreen, OUTPUT);
pinMode (pushButton, INPUT);
}
void loop() {
int ldrStatus = analogRead(ldr);
buttonState = digitalRead(pushButton);
if (ldrStatus <= 900) {
digitalWrite(ledRed, HIGH);
digitalWrite(ledGreen, LOW);
Serial.print("FAIL");
Serial.println(ldrStatus);
}
else {
digitalWrite(ledGreen, HIGH);
digitalWrite(ledRed, LOW);
Serial.print("VALID");
Serial.println(ldrStatus);
}
}
You need a boolean to track the "alarm" state as I call it. Here is my take take on it. It compiles but I have not fully tested it. Also, I changed the button to INPUT_PULLUP and assumed the pressed state was LOW. Yours may be wired differently.
const int ldr = A0; //ldr pin A0
const int ledRed = 13; //red Led pin 13
const int ledGreen = 12; //green Led pin 12
const int pushButton = 2; //pushButton in pin 2
int lastButtonState;
bool ldrAlarm = false;
bool lastLdrAlarm = false;
void setup() {
Serial.begin(9600);
pinMode(ldr, INPUT);
pinMode(ledRed, OUTPUT);
pinMode(ledGreen, OUTPUT);
pinMode(pushButton, INPUT_PULLUP);
lastButtonState = digitalRead(pushButton);
digitalWrite(ledRed, LOW);
digitalWrite(ledGreen, HIGH);
}
void loop() {
int ldrStatus = analogRead(ldr);
int buttonState = digitalRead(pushButton);
if (buttonState != lastButtonState)
{
delay(50); // debounce
lastButtonState = buttonState;
if (buttonState == LOW)
{
ldrAlarm = false;
}
}
if (ldrStatus <= 900) {
ldrAlarm = true;
}
else {
Serial.print("VALID");
Serial.println(ldrStatus);
}
if (ldrAlarm != lastLdrAlarm) {
lastLdrAlarm = ldrAlarm;
if (ldrAlarm) {
digitalWrite(ledRed, HIGH);
digitalWrite(ledGreen, LOW);
Serial.print("FAIL ");
Serial.println(ldrStatus);
}
else {
digitalWrite(ledGreen, HIGH);
digitalWrite(ledRed, LOW);
}
}
}