I'm only beginner on this stuff, so I decided to do something easy, while doing this easy task of mine I encountered a little problem. I was trying to make dimming light, when ultrasound detects it at certain point, the light either fades in completely or fades out completely. Here's the code:

The problem is when i reset, for the first time round works just right. It fades in when the distance is <= 25 and fades out when the distance is > than 25. But for the second or any other time it just turns on or off, the fading effect disappears. What am I doing wrong? Should I add one more delay somewhere?