At times it is useful to get activities in your firmware synced up with external events.
There are several types of events that are dependent of the speed, frequency, state, ... of something external.
In this blog, I'm showing martinvalencia's solution to synchronise a microcontroller PWM signal with an external clock.
image: a blue 20 kHz signal kept under control of an external 60 Hz pulse
The PWM is (in this example) 20 kHz. The external clock is a 60 Hz signal.
Those two values are selected because they show up nicely on an oscilloscope. They 'll allow you to see the syncing vs. not-syncing.
In a real world example, the 60 Hz could be the zero-crossing point of your utility line. And the PWM signal a 3-phase signal generated by your controller, syncing up with the line power.
video: the 20 kHz signal synked by the external 60 Hz signal, control released and control regained
What Does it Do?
Every time the controlling signal has a rising edge, the PWM signal is reset.
It's current activity, whether it was high or low, regardless of however long it was high or low, will be stopped and discarded.
The PWM will start generating as if it's just been switched on.
You can see this as a triggered restart.
Setting up de Peripherals
You need to enable the PWM driver, because that's the one that 'll be used both for detecting the sync pulses and generating the PWM.
This is done vie the HALCoGen application for Hercules controllers.
Then in the PWM settings, enable the 1st one, and set its behaviour.
Then the Pin Multiplexer. This is different for the RM46 and 57 (and the same different for their TMS570LS12 TMS570LC43 twins).
RM46:
RM57:
That's it. Let HALCoGen generate the project code.
Source Code
Very simple. It sets that the counter (re)loads on sync.
etpwmInit(); etpwmEnableCounterLoadOnSync(etpwmREG1, 0, COUNT_UP); while (1) { }
The behaviour is as you can see in the video at the start of this article.
If no external pulse, the PWM happily pulses at its set frequency. Each time the external sync pulse is detected, the PWM resyncs on that event.