题解 | #信号发生器#
信号发生器
https://www.nowcoder.com/practice/39f6766689cc448e928a0921d1d1f858
`timescale 1ns/1ns
module signal_generator(
input clk,
input rst_n,
input [1:0] wave_choise,
output reg [4:0]wave
);
//三角波发生时首先是先向下
reg [4:0]cnt;
reg up;
always@(posedge clk or negedge rst_n) begin
if(~rst_n)
begin
wave<=5'd0;
cnt<=5'd0;
end
else case(wave_choise)
2'b00://方波
begin
if(cnt==5'd19)
begin
wave<=5'd0;
cnt<=5'd0;
end
else if(cnt==5'd9)
begin
wave<=5'd20;
cnt<=cnt+1'd1;
end
else begin
wave<=wave;
cnt<=cnt+1'd1;
end
end
2'b01://锯齿波
begin
if(wave==5'd20)
begin
wave<=5'd0;
end
else
begin
wave<=wave+1'd1;
end
end
2'b10:begin//三角波
if(wave==5'd20)
begin
wave<=wave-1'd1;
up<=1'd0;
end
else if(wave==5'd0)
begin
wave<=wave+1'd1;
up<=1'd1;
end
else if(up)
wave<=wave+1'd1;
else wave<=wave-1'd1;//先向下操作
end
default:
begin
wave<=5'd0;
end
endcase
end
endmodule
module signal_generator(
input clk,
input rst_n,
input [1:0] wave_choise,
output reg [4:0]wave
);
//三角波发生时首先是先向下
reg [4:0]cnt;
reg up;
always@(posedge clk or negedge rst_n) begin
if(~rst_n)
begin
wave<=5'd0;
cnt<=5'd0;
end
else case(wave_choise)
2'b00://方波
begin
if(cnt==5'd19)
begin
wave<=5'd0;
cnt<=5'd0;
end
else if(cnt==5'd9)
begin
wave<=5'd20;
cnt<=cnt+1'd1;
end
else begin
wave<=wave;
cnt<=cnt+1'd1;
end
end
2'b01://锯齿波
begin
if(wave==5'd20)
begin
wave<=5'd0;
end
else
begin
wave<=wave+1'd1;
end
end
2'b10:begin//三角波
if(wave==5'd20)
begin
wave<=wave-1'd1;
up<=1'd0;
end
else if(wave==5'd0)
begin
wave<=wave+1'd1;
up<=1'd1;
end
else if(up)
wave<=wave+1'd1;
else wave<=wave-1'd1;//先向下操作
end
default:
begin
wave<=5'd0;
end
endcase
end
endmodule