The code functions with every object working, but I have a delay issue that I cannot figure out and I believe it's something in the loop aspect of the code.
Desired effect is that a photo sensor detects light. If no light, detect motion. On motion, fade LED(s) up. After specified delay, fade LED(s) down. repeat.
What's happening is that the LED(s) are staying on for about 90 seconds despite a 1ms delay (actual desire is 5000ms delay). It does eventually fade out as intended and shut off when exposed to light. Everything but the delay is working as intended.
I'm expecting that the following code functions as a delay to keep the LED(s) on, once initiated; however, when I set it to "0", I see that the LED(s) are fading up and down over and over without motion. I did something wrong and I'm not seeing it. It's so damn close, but not there yet.
const long interval = 1
I set it to "1" because everything larger is just more unnecessary delay to seeing a reaction.
The full source code for the project
#define LEDPIN 3
#define PIRPIN 2
#define LDR 0
int ldrValue = 0;
int ledState = 0;
unsigned long previousMillis = 0;
unsigned long currentMillis = 0;
boolean alreadyfadedup = false;
boolean alreadyfadeddown = false;
const long interval = 1; //amount of time the leds will stay up in millis
void setup() {
pinMode(PIRPIN, INPUT);
}
void loop() {
ldrValue = analogRead(LDR);
currentMillis = millis();
if(ldrValue <= 512) {
analogWrite(LEDPIN,0);
}
else {
if (digitalRead(PIRPIN) == 1) {
ledState = 1;
previousMillis = currentMillis;
if (alreadyfadedup == false) {
for (int i = 0; i < 256; i++) {
analogWrite(LEDPIN, i);
delay(17);
}
alreadyfadedup = true;
alreadyfadeddown = false;
}
}
if (currentMillis - previousMillis >= interval) {
if (ledState == 1) {
if (alreadyfadeddown == false) {
for (int i = 255; i >= 0; i--) {
analogWrite(LEDPIN, i);
delay(17);
}
alreadyfadeddown = true;
alreadyfadedup = false;
}
ledState = 0;
}
else{
analogWrite(LEDPIN,0);
}
}
}
}