Project: PWM Generator
Pulse-width modulation from a counter and a comparator — the way FPGAs dim LEDs and drive motors.
Pulse-width modulation switches an output on for part of every period. Averaged by an LED's perception, a motor's inertia or an RC filter, the duty cycle acts like an analog level. In hardware it takes just a free-running counter and a comparator.
Real-world details
assign out = (cnt < duty); // combinational output always @(posedge clk) out <= (cnt < duty);
The comparator output can glitch while cnt changes bits. Registering it gives a clean signal for the pin.
With a 50 MHz clock and an 8-bit PWM counter, what is the PWM frequency?
50,000,000 / 256 = about 195 kHz.
Why does this PWM never reach 100% duty, and how would you allow it?
out is high while cnt < duty, and duty is at most 15 while cnt reaches 15, so at best 15 of 16 clocks are high. Make duty one bit wider (0..16) or use <= with a special case for full on.