I recently came across the problem that I needed a PWM (i.e. pulse-width modulated rectangular signal) generator block in Simulink with variable frequency and duty cycle inputs. I couldn’t find one in the library, so I wrote one.
The rather simple implementation basically consists of three parts: An integrator block with an external reset input is used to create a sawtooth signal. The sawtooth is then compared to a threshold value given by means of the duty cycle to create a rectangular signal. Lastly that signal is scaled to a standard output range of 0..1.
The edge or level triggered reset input can be enabled in the integrator’s block properties. The block is then wired to integrate the frequency value and be reset whenever the output crosses the value of one. This can be realized by subtracting one and comparing the result to zero.
The resulting sawtooth signal then looks like the following, assuming a constant frequency of 1Hz:
By subtracting the sawtooth from the duty cycle „factor“ and taking the sign, the rectangular signal is created. Since the sign block creates values in the range of -1..1, a shift and scale is applied to bring it to the range of 0..1.
This is what the result looks like with a frequency of 1Hz and a duty cycle of 25% (like in the first picture):
When applying a frequency ramp – 1Hz/s in the following example – with the same duty cycle of 25%, a chirp-like output signal is created:
And this is what it looks like when keeping a constant frequency (1Hz again) while ramping down the duty cycle by 25%/s from 100%:
That last example is a bit counter-intuitive though as the duty cycle is reduced continually (as opposed to every second), which is – for example – why there is no segment of 100% duty cycle; but you’ll get the idea.