Close

PWM module verilog HDL code

A project log for Super custom PWM - FPGA

Make a FPGA with lots of PWM ports, all of them 32 bit, and easy to program!

sciencedude1990sciencedude1990 11/02/2020 at 04:000 Comments

// PWM module
// inputs
//    clk - the clock signal, will use posedge
//    max_count - the highest count value of the counter
//    compare_val - the comparison value for the counter
// outputs
//    cmp - compares the internal counter to compare_val
//
// note
//    a counter that always counts up to max_count
//    compares the counter to compare_val - if the counter is lower, output 1, otherwise output 0

module pwm_module(
input wire clk,
input wire [31:0] max_count,
input wire [31:0] compare_val,
output wire cmp
);

// Internal counter
reg [31:0] cnt;

// Set to 0 at start
initial begin
cnt <= 32'h00000000;
end

always @(posedge clk) begin

if (cnt < max_count) begin
// If the counter is less than max_count, increment
cnt <= cnt + 32'h00000001;
end else begin
// otherwise, set to 0
cnt <= 0;
end
end

// When count is less than the compare value, output 1, otherwise 0
assign cmp = (cnt < compare_val) ? 1'b1 : 1'b0;

endmodule

Discussions