PIR sensing with fade effect

Hello, i am from Bulgaria. I am working on Arduino from several months and I am very interested. Last days i am trying to make a PIR LED control. What I mean? I have a PIR motion sensor with 3 legs - VCC, OUT and GND. I want to make the following: when i have HIGH the led is light up. But when i have LOW i want to fade the LED with PWM(255-0) and when it's 0 the led should turn off untill the next HIGH value trigered by the PIR sensor. I have tried several ways to fade the led. They are working, but the LED never turn off. The fading is looping again and again through the loop function and i am watching a "breathing" effect. I can't understand how to turn off the led at the end of loop until the next HIGH.
I have tried with "FOR" cycle. I have tried with "DO/WHILE", i have tried with "value-=number" and there was infinite loop of fading or flickering the led. Please write me a simple program that turn off the led after the fade effect.

I'm guessing that you are not sensing the change in PIR state correctly. try something like shown below

int previous_state=0;


void loop()
{

state=digitalRead(PIR_pin); // or whatever you do to read the PIR

if (state == HIGH && previous_state==LOW) {
   // turn on your LED
   
}

if (state == LOW && previous_state==HIGH) {
   // fade out your LED
}

previous_state=state;

}

hi !

like in the previous reply, just add flags in your code, and then, test them if you want to do something or not.

have a nice day

Thanks a lot. The idea is working, but i want to power the led at full brightness when PIR detects movement during fading.

this is the code:

int lampa = 11;
int senzor = 2;
int previous_state=0;
void setup(){
pinMode(11, OUTPUT);
pinMode(2, INPUT);

}
void loop(){

int state=digitalRead(2); // or whatever you do to read the PIR

if (state == HIGH && previous_state==LOW) {
digitalWrite(11, HIGH);

}

if (state == LOW && previous_state==HIGH) {
for(int k=255; k>=0; k-=5){
analogWrite(11, k);
delay(30);
}
}
previous_state=state;
}

but when i move for example my hand during fading - nothing happens. The led just power off and then power up again...i want if it get faded and a move my hand, the led get full brightness...

Please help me...

Your fade for-loop has to run completely before it goes back and checks the status of the PIR input again. In order to get the behavior you want you will have to arrange for the analogwrite() to occur in the outer loop or check the status of the PIR inside the for-loop and exit if it goes high again (the 'break' statement is useful here).