Another way to get a long fade down would be to use the 'time' variable which increments every second and calculate what the duty should be at a specific time. That is, there are 1200 seconds in 20 minutes, so the duty can be the inverse of that, decreasing from 1200 to 0 over that time.
Unfortunately 1200 is too large for a duty ( which has a maximum of 1023 ) but a 1023 to 0 duty can be calculated from a 1200 to 0 time -
duty = ( 1200 - ( time Max 1200 ) ) * ( 1023 / 1200 )
Alternatively, the maths can be made simpler and the PWM frequency adjusted to match what the duty may be. For example a 1200 to 0 can be easily converted to 600 to 0, and with a maximum duty of 600 for 100% brightness requiring a frequency of 150 ( freq = maxDuty / 4 ).
For dimming a higher maximum duty is best so a duty of 900 to 0 and a frequency of 225 is better.
duty = ( 1200 - ( time Max 1200 ) ) * ( 900 / 1200 )
That 900/1200 is a simpler 3/4. Untested ...
Code:
Initialise:
PwmOut pwmPin, 225, 900
WaitForButtonPush:
Do : Loop until Pbswitch = 1
FadeDown:
time = 0
Do
val = time Max 1200
val = 1200 - val * 3 / 4
PwmDuty pwmPin, val
Loop Until val = 0
The 'time Max 1200' is defensive programming, to handle the case should 'time' ever get higher than 1200. If there is no risk of that then the maths can be simplified -
val = 1200 - time * 3 / 4