The code you posted doesn't really do anything... you're checking the value of "val" which is a pretty bad variable name (all variables hold values) - but you never update the value of val. Val will always be zero with the code you posted.
This needs to be a "state machine" - it has two states - CurrentlyDimming true, and CurrentlyDimming false. That state is set by your button. First, work up the code that lets you change state, and do something simple to indicate it - like turn on the LED when "CurrentlyDimming" is true. Then set up your sine wave brightness loop to run while continually checking the button, and make your button stop the animation where it is - then when you get that working, try making the light dim while the button is held down. Then your requirement will be met.
You need to go through each line of the code (It's not very long) and work out exactly what the line does. Ideally, put a comment at the end of each line.
And as mentioned above, please go back and modify your first post and put the code inside [ code] [ /code] tags.
No this is code I have patched together from others testing various things.
I have got a nice loop i like, and using the if statement, i can turn my led off set it at a designated pwm duty cycle value however I wish to simulate a sunset over a longer period.
wire pin 7 so pin is grounded when button is pressed
Looks like it would fade down in 1/2 second intervals as written.
Missing a few things:
What assigns the initial PWM values?
What will bring it back up?
If the button is pressed again while it is off, it will re-fade again.
All easily fixed once you define its operation in more detail.
dumpstar85:
I am specifically looking for a PWM fade out code which will allow a transition from 255 to 0 smoothly.
I am currently reading about state changing however this was not my question.
Yes it was...
When flick a switch, i want this to slowly fade from its pwm loop value at the time to a lower 'if' value which would make the led appear dimmer.
That is a question asking how to manage a state change -> when flick a switch. You want something to happen differently when the switch is flipped - that's a state change. And, you asked about it.
Please do not accuse us of not being able to read, when you post unclear questions. I gave you lots of good information and it doesn't come out instantly, we have to spend time on these answers. Please do your best to appreciate that. Thanks.