思路:方波的周期是20,锯齿波的周期是21,三角波的周期是40,且wave 的最大值是20,题目没有明确告知,所以使用case语句。
`timescale 1ns/1ns
/*题目描述:
请编写一个信号发生器模块,根据波形选择信号wave_choise发出相应的波形:
wave_choice=0时,发出方波信号;
wave_choice=1时,发出锯齿波信号;
wave_choice=2时,发出三角波信号。
*/
module signal_generator(
input clk,
input rst_n,
input [1:0] wave_choise,
output reg [4:0] wave
);
reg [5:0] count;
reg flag;
always@(posedge clk or negedge rst_n)begin
if(!rst_n)begin
wave <= 5'd0;
count <= 6'd0;
flag <= 0;
end
else begin
case(wave_choise)
2'b00:begin
if(count==6'd9)begin
wave <= 6'd20;
count <= count + 6'd1;
end
else if(count==6'd19)begin
wave <= 6'd0;
count <= 6'd0;
end
else begin
wave <= wave;
count <= count + 6'd1;
end
end
2'b01:begin
if(wave==6'd20)
wave <= 6'd0;
else
wave <= wave + 6'd1;
end
2'b10:begin
if(flag)begin
if(wave<6'd20)begin
flag <= flag;
wave <= wave + 6'd1;
end
else if(wave==6'd20)begin
flag <= ~flag;
wave <= wave - 6'd1;
end
end
else begin
if(wave>6'd0)begin
flag <= flag;
wave<= wave - 1;
end
else if(wave==6'd0)begin
flag <= ~flag;
wave <= wave + 1;
end
end
end
endcase
end
end
endmodule
注意:在三角波时注意设置标志位,flag=1是下降,反之上升
解法二:简化版
`timescale 1ns/1ns
/*题目描述:
请编写一个信号发生器模块,根据波形选择信号wave_choise发出相应的波形:
wave_choice=0时,发出方波信号;
wave_choice=1时,发出锯齿波信号;
wave_choice=2时,发出三角波信号。
*/
module signal_generator(
input clk,
input rst_n,
input [1:0] wave_choise,
output reg [4:0] wave
);
reg [5:0] count;
reg flag;
always@(posedge clk or negedge rst_n)begin
if(!rst_n)begin
wave <= 5'd0;
count <= 6'd0;
flag <= 0;
end
else begin
case(wave_choise)
2'b00:begin
if(count==6'd9)begin
wave <= 6'd20;
count <= count + 6'd1;
end
else if(count==6'd19)begin
wave <= 6'd0;
count <= 6'd0;
end
else begin
wave <= wave;
count <= count + 6'd1;
end
end
2'b01:begin
if(wave==6'd20)
wave <= 6'd0;
else
wave <= wave + 6'd1;
end
2'b10:begin
if(flag)begin
if(wave<6'd20)begin
flag <= flag;
wave <= wave + 6'd1;
end
else if(wave==6'd20)begin
flag <= ~flag;
wave <= wave - 6'd1;
end
end
else begin
if(wave>6'd0)begin
flag <= flag;
wave<= wave - 1;
end
else if(wave==6'd0)begin
flag <= ~flag;
wave <= wave + 1;
end
end
end
endcase
end
end
endmodule
Testbench
`timescale 1ns/1ns
module testbench();
reg clk,rst_n;
reg [1:0]wave_choise;
wire [4:0]wave;
initial begin
$dumpfile("out.vcd");
$dumpvars(0,testbench);
clk = 0;
rst_n = 0;
end
initial begin
wave_choise = 2'b00;
#17 rst_n =1;
#800 wave_choise = 2'b00;
#800 wave_choise = 2'b01;
#800 wave_choise = 2'b10;
#800 wave_choise = 2'b00;
#800 $stop;
end
always #5 clk = !clk;
signal_generator dut(
.clk(clk),
.rst_n(rst_n),
.wave_choise(wave_choise),
.wave(wave)
);
endmodule