FADING LED

HELP!!!

OK So I am trying to make a bed light so my wife wont have to walk around in the dark at night.

Basically I want this to happen.

motion sensor goes off.

Light fades on.

wait for X mins

light fades off.

I am using the the base code I found off the net, and trying to modify it by adding pasting in someone else fade code. which is a problem because, in the original code it is. If x happens set 3 to HIGH, and I want to it to be. If X happens run this code.

Here is my code.

// Motion Sensor with fading LED

int value = 0; // variable to keep the actual value
int ledpin = 9; // light connected to digital pin 9

void setup() {

int sensor = 9;
pinMode(sensor,INPUT);
pinMode(3,OUTPUT);
}

void loop() {
int sensor = 9; if (digitalRead(sensor) == HIGH ) digitalWrite( // ← here is where I think the problem is.

3,
fade(); {
for(value = 0 ; value <= 255; value+=5) // fade in (from min to max)
{
analogWrite(ledpin, value); // sets the value (range from 0 to 255)
delay(150000); // waits for 5 minutes
}
for(value = 255; value >=0; value-=5) // fades down
{
analogWrite(ledpin, value);
delay(30);
}
}
)
else digitalWrite(3,LOW);

}

You should make sensor a global variable, instead of having two local variables with the same name in two different functions.

You should learn to create functions. Put the code to fade the LED in a function.

void fade()
{
 for(value = 0 ; value <= 255; value+=5) // fade in (from min to max)
 {
   analogWrite(ledpin, value);           // sets the value (range from 0 to 255)
   delay(1500000);                            // waits for 5 minutes 
 }
 for(value = 255; value >=0; value-=5)   // fades down
 {
   analogWrite(ledpin, value);
   delay(30);
 }
}

Then, when you want to fade an LED, just call the function.

Notice just how long it will take that LED to fade up. 55 steps of 15 minute duration will take 14+ hours to fade up.

You probably want the LED to fade up with 30 millisecond pauses between steps and a 15 minute pause before the for loop to fade back down.

By putting the code to fade the LED in a function, you will have a much smaller loop(), and it will be much more obvious what the problem is.

Your loop() function then looks like so:

void loop() {
int sensor = 9; if (digitalRead(sensor) == HIGH ) digitalWrite(  
3,
fade();                                                                                                   )
else digitalWrite(3,LOW);

}

which I think you can see is nonsense. Writing the value fade() to a digital pin does not make sense.