14. PWM generator
Generate a pulse-width modulated signal with a period of 16 clock cycles.
A 4-bit counter runs 0 to 15 and wraps. pwm is 1 while the counter is less than the captured duty value, so a duty of 0 is always off and a duty of 15 is on for 15 cycles out of 16.
To avoid odd-length pulses when duty changes in the middle of a period, the duty input is captured only at the start of a period: on the edge where the counter wraps from 15 to 0, and also on a reset edge. pwm uses the captured value, never the live input.
rst (synchronous, active high) sets the counter to 0 and captures duty.
Ports
| Port | Dir | Bits | What it is |
|---|---|---|---|
clk | in | 1 | Clock. |
rst | in | 1 | Synchronous reset; also captures duty. |
duty | in | 4 | Requested on-time in cycles per 16. |
pwm | out | 1 | PWM output. |
Example
With duty = 4 captured, pwm is 1 for counter values 0 to 3 and 0 for 4 to 15. Changing duty to 10 when the counter is at 4 changes nothing until the counter wraps to 0.
Written hints
AI hint
Submissions
No submissions yet. Submit your answer and it shows here. Sign in to keep them.
Submit your answer to have it graded. The hidden test runs on the server; you see whether it passes and, if not, the first case it gets wrong.
Press Build to check your code with Yosys. Errors and warnings show here, and a clean build draws the logic diagram.
Build your design to drive it by hand and see its signals here.