I'm implementing a digital phase-locked loop with an STM32F303CCT6. I basically need to lock in to a square wave coming in (but I also need to have the possibility to detune the frequency or do sanity checks on it) and output a 50% duty cycle PWM-signal out with the same frequency and phase. The frequency is in the range of maybe 40-60kHz.
Currently I have a setup where I measure the time between the rising edge of the reference signal (with a comparator triggering a timer) and the rising edge of the PWM-signal (so kinda like a XOR phase detector). This time difference is used as an input to a PID-controller (no integral parameter since it's a self-integrating process) which controls the period register on the advanced-control timer I'm using.
My current setup almost works, it locks to the frequency alright but the phase is all over the place. I played around a lot with the PD-parameters yesterday and I couldn't make it any better. It basically seems to lock to the frequency with pretty much any parameters but otherwise I'm having a hard time saying anything concrete about the effect of the parameters (just a subjective guess that "this MIGHT have less jittering and phase running around").
I have a feeling the I might need to be able to somehow "synchronize" the PWM-timers phase to the reference signal but I'm not sure how. Only thing I can think of is just resetting the whole counter and starting again when the comparator gets an edge from the reference signal but this doesn't seem right (I would get distorted cycles with non 50% duty cycle etc. and maybe even some additional glitches).
Any ideas on how to achieve this? Is there something fundamentally wrong with my "algorithm"? Is there a better way to quantify the performance (looking at the square waves with my DS1074Z is almost useless because the phase is jittering so much that the other square wave is just a blur)?
Btw. I ran in to this article:
http://edn.com/design/test-and-measurement/4323787/Two-gates-and-a-microprocessor-form-digital-PLL which is pretty much what I want to achieve but I would like to avoid extra hardware (if possible). Also I cannot do that clock gating trick with this ARM if I want to use the high-frequency doubled PLL clock for the timer (for better frequency resolution). I'm also not totally sure what is the point of the clock gating trick?