I am not so experienced as others here, but would offer what help and encouragement that I may. It is my experience that coding never fails, some outside factor is introducing change. Odd behavior is often a power issue. Is your power well suppled? Does the pwm continue during the problem? I did not see configuration; could it be watchdog, a poor ground or other exteral condition?