Syncronise PWM or similar to input for dimmer

Hi,

I know this has been discussed a number of times before but not quite the same.

What I am trying to achieve is a 240V 50Hz dimmer to control a 40A load. The electronics side is easy, a simple zero crossing detector and a random turn-on SSR.

I have written the code that will run the dimmer using an interrupt for the zero crossing and then checking the micros() in a loop until I hit the magic number etc.

It all works quite well as long as I don't get adventurous and try to send / receive serial or do any other work with the Mega 2560.
As soon as I introduce extra tasks I start to get jitter in the output. As I will be controlling a universal motor as well as heating elements I want a really stable output.

It seems a bit of a waste to need a separate Arduino to just run the dimmer outputs.

What I would like to do is either synchronize the PWM to the zero crossing and then let it all be done in hardware so I have time to do other things.
I notice from the data sheet that I can turn off the clock to the pwm and write to the counters by software but I am hoping to not need to do that as I will still need to do a time sensitive interrupt each 20mS.

thanks for reading
Lee

I think you need to use timer interrupts to manage your delay using timer1, rather than busy waiting in code. There may be a library to hide all the details.