题解 | #信号发生器#
信号发生器
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 ); //方波的周期是20,锯齿波的周期是21,三角波的周期是40,且wave的最大值是20。 reg [4:0]cntf; reg [4:0]cntj; reg [4:0]cnts; reg flag; //assign flag=(wave==0 || wave==5'd20)?~flag:flag; always@(posedge clk or negedge rst_n)begin if(!rst_n) cntf<=5'b0; else if(cntf>=20-1) cntf<=5'b0; else cntf<=cntf+1; end always@(posedge clk or negedge rst_n) begin if(!rst_n) wave<=5'b0; else if (wave_choise==0) begin wave <= cntf<9?0:cntf<19?20:0; end else if(wave_choise==1)begin wave<=cntj; end else if(wave_choise==2)begin wave <= flag==0 ? wave-1: wave+1; end end always@(posedge clk or negedge rst_n)begin if(!rst_n) cntj<=5'b0; else if(wave_choise==1) begin if(cntj>=21-1) cntj<=5'b0; else cntj<=cntj+1; end end always@(posedge clk or negedge rst_n)begin if(!rst_n) cnts<=5'b0; else if(cnts>=20-1) cnts<=5'b0; else cnts<=cnts+1; end reg flag1; always @(posedge clk or negedge rst_n) begin if (~rst_n) begin flag <= 0; end else begin if (wave_choise != 2) begin flag <= 0; end else begin if (wave == 1) begin flag <= 1; end else if (wave == 19) begin flag <= 0; end else begin flag <= flag; // 保持 flag 不变 end end end end endmodule