之前的因为一些问题发的code有点问题,这次把更新之后code发了出来,虽然也不是很完善但是初步还是可以用的;
对应的code如下:
`timescale 1ns / 1ps
module creat_PWM
(
input wire clk,
input wire rst,
input wire key_flag1,
input wire key_flag2,
input wire key_flag3,
input wire key_flag4,
output reg PWM
);
reg [1:0] Frequency_seting;
always @(posedge clk or negedge rst)
if( rst == 1'b0 )
Frequency_seting <= 2'b00;
else if( (Frequency_seting == 2'b11) && (key_flag3==1'b1) )
Frequency_seting <= 2'b00;
else if( (Frequency_seting == 2'b00) && (key_flag4==1'b1) )
Frequency_seting <= 2'b11;
else if( key_flag3==1'b1 )
Frequency_seting <= Frequency_seting + 1'b1;
else if( key_flag4==1'b1 )
Frequency_seting <= Frequency_seting - 1'b1;
else
Frequency_seting <= Frequency_seting;
reg [23:0] Frequency_CNT_MAX;
always @(posedge clk or negedge rst)
if( rst == 1'b0 )
Frequency_CNT_MAX <= 24'd9_999;
else case( Frequency_seting )
2'b00 : Frequency_CNT_MAX <= 24'd9_999;
2'b01 : Frequency_CNT_MAX <= 24'd99_999;
2'b10 : Frequency_CNT_MAX <= 24'd999_999;
2'b11 : Frequency_CNT_MAX <= 24'd9_999_999;
default : Frequency_CNT_MAX <= 24'd9_999;
endcase
reg [23:0] counter;
always @(posedge clk or negedge rst)
if( rst == 1'b0 )
counter <= 0;
else if( counter == Frequency_CNT_MAX)
counter <= 0;
else
counter <= counter + 1'b1;
reg [23:0] duty_counter;
always @(posedge clk or negedge rst)
if( rst == 1'b0 )
duty_counter <= Frequency_CNT_MAX/2;
else if( key_flag1 == 1'b1 )
duty_counter <= duty_counter + (Frequency_CNT_MAX/10);
else if( key_flag2 == 1'b1 )
duty_counter <= duty_counter - (Frequency_CNT_MAX/10);
else
duty_counter <= duty_counter;
always @(posedge clk or negedge rst)
if( rst == 1'b0 )
PWM <= 1'b0;
else if( duty_counter <= counter )
PWM <= 1'b1;
else
PWM <= 1'b0;
endmodule
对应的测试用的testbench如下:
`timescale 1ns/1ns
module tb_creat_PWM();
//****************** Parameter and Internal Signal *******************//
//wire define
wire PWM;
//reg define
reg clk;
reg rst;
reg key_flag1;
reg key_flag2;
reg key_flag3;
reg key_flag4;
//***************************** Main Code ****************************//
initial begin
clk = 1'b1;
rst <= 1'b0;
key_flag1 <= 1'b0;
key_flag2 <= 1'b0;
key_flag3 <= 1'b0;
key_flag4 <= 1'b0;
#201;
rst <= 1'b1;
#200;
key_flag1 <= 1'b1;
#100;
key_flag1 <= 1'b0;
#20000000;
key_flag1 <= 1'b1;
#100;
key_flag1 <= 1'b0;
#20000000;
#20000000;
$stop;
end
// creator clk
always #10 clk <= ~clk;
//*************************** Instantiation **************************//
creat_PWM creat_PWM_inst
(
.clk ( clk ),
.rst ( rst ),
.key_flag1 ( key_flag1 ),
.key_flag2 ( key_flag2 ),
.key_flag3 ( key_flag3 ),
.key_flag4 ( key_flag4 ),
.PWM ( PWM )
);
endmodule
对应的原始code中的参数如果修改一下是可以大幅缩短仿真时间,但是一时没有想起对应的修改模块内部变量的方法,后面找到后再进行补充。
写的还是感觉比较差劲,只能说说慢慢进步吧,自己也是自学不久。