module PWM_generator_v2 ( // inputs: address, chipselect, clk, reset_n, write_n, writedata, // outputs: out_port, dir_port, readdata ) ; output out_port; output [1:0] dir_port; output [ 31: 0] readdata; input [ 1: 0] address; input chipselect; input clk; input reset_n; input write_n; input [ 31: 0] writedata; reg [ 31: 0] data_reg0,data_reg1,data_reg2; reg out_port; reg [1:0] dir_port; reg [ 31: 0] readdata; reg [ 31: 0] count; always @(posedge clk or negedge reset_n) begin if (reset_n == 0) begin data_reg0 <= 0; data_reg1 <= 0; end else if (chipselect && ~write_n && (address == 0)) data_reg0 <= writedata[31 : 0]; else if (chipselect && ~write_n && (address == 1)) data_reg1 <= writedata[31 : 0]; else if (chipselect && ~write_n && (address == 2)) data_reg2 <= writedata[31 : 0]; end always @(posedge clk or negedge reset_n) begin if (reset_n == 0) begin readdata <= 0; end else if (chipselect && (address == 0)) readdata <= data_reg0; else if (chipselect && (address == 1)) readdata <= data_reg1; else if (chipselect && (address == 2)) readdata <= data_reg2; end always @ (posedge clk or negedge reset_n) begin if (reset_n == 0) count <= 0; else begin if (count < data_reg1) count <= count + 1; else count <= 0; end end always @ (posedge clk) begin if (count < data_reg0) out_port <= 1; else out_port <= 0; end always @ (posedge clk) begin if (data_reg2==0) dir_port<=2'b00; else if (data_reg2[31]==0) dir_port<=2'b01; else dir_port<=2'b10; end endmodule