Close

PWM works on the FPGA!

A project log for FPGA dabbling

I don't need an FPGA for anything but the fun of experimenting with it.

christophChristoph 12/07/2018 at 20:550 Comments

So I managed to write a top module for the PWM module I came up with. Here it is:

module top(
  input i_clk12,
  output o_led);

reg reset = 0;
wire pwm_out;

wire clk_dc;
reg[15:0] dc = 0;
clockdivider clkdiv(i_clk12, 12000000, clk_dc);

pwm #(.bits(16)) pwm0(i_clk12,reset,16'd15999,dc,pwm_out);
always @(posedge clk_dc)
begin
  dc <= (dc == 16000) ? 0 : (dc + 4000);
end

SB_IO #(                // IO IP instance
  .PIN_TYPE(6'b011001)  // configure as output
) pin_out_driver (
  .PACKAGE_PIN(o_led),  // connect to this pin
  .D_OUT_0(pwm_out)     // output the state of "led"
);

endmodule

It cycles through 5 duty cycle levels (on per second). Reset isn't used, but that's not too critical here I guess.

This is the pwm code:

module pwm #(
  parameter bits = 4
  )(
  input clkin,
  input reset,
  input[bits-1:0] max,
  input[bits-1:0] compare,
  output out
);

reg[bits-1:0] count = 0;
reg[bits-1:0] compareLatched = 0;

always @(posedge clkin)
begin
  if(reset == 1)
    begin
      count <= 0;
      compareLatched <= 0;
    end
  else
    begin
      if(count == 0)
        begin
          count <= max-1;
          compareLatched <= compare;
        end
      else
        count <= count-1;
    end
end
assign out = count < compareLatched;

endmodule

 Pins:

set_io i_clk12 21
set_io o_led 96

This is for #ICEd = an Arduino Style Board, with ICE FPGA  

Discussions