题意整理

       题目要求编写一个十进制计数器,即输出数值number每次变化1,在0-9之间循环。根据mode信号的值,更改输出数值number的变化方向。可以将mode作为判断条件,使用if-else语句实现不同的变化方向。

题解主体

       首先确定zero的取值逻辑,在默认情况下为0,当number=0时,zero值为1。       always @(posedge clk or negedge rst_n)

              if (!rst_n)

                     begin

                            zero <= 1'd0;

                     end

              else if (number == 4'd0)

                     begin

                            zero <= 1'b1;

                     end

              else

                     begin    

                            zero <= 1'b0;

                     end

       然后将mode的值作为if-else的判断条件,当mode为1时,number每个时钟周期加一,当mode为0时,number每个时钟周期减一。

       always @(posedge clk or negedge rst_n)

              if (!rst_n)

                     begin

                            number <= 4'b0;

                     end

              else if(mode)

                     begin

                            number <= number + 1'd1;

                     end

              else if(!mode)

                     begin

                            number <= number - 1'd1;

                     end

              else number <= number;

       按照以上代码,因为判断number==4’d0需要一个时钟,zero信号为1,总是滞后number==0一个时钟周期。所以可以考虑将number延迟一个时钟再输出。使用num变量代替上述的number,再通过以下语句实现number延迟一个时钟输出。

reg [3:0]num;

       always @(posedge clk or negedge rst_n)

              if (!rst_n)

                     begin

                            number <= 4'd0;

                     end

              else

                     begin    

                            number <= num;

                     end

参考答案

`timescale 1ns/1ns

module count_module(
	input clk,
	input rst_n,
	input mode,
	output reg [3:0]number,
	output reg zero
	);

	reg [3:0]num;
	always @(posedge clk or negedge rst_n)
		if (!rst_n)
			begin 
				zero <= 1'd0;
			end
		else if (num == 4'd0)
			begin
				zero <= 1'b1;
			end
		else 
			begin	
				zero <= 1'b0;
			end
		
	always @(posedge clk or negedge rst_n)
		if (!rst_n)
			begin 
				num <= 4'b0;
			end
		else if(mode)
			begin
				if(num == 9)
					num <= 0;
				else
					num <= num + 1'd1;
			end
		else if(!mode)
			begin
				if(num == 0)
					num <= 9;
				else
					num <= num - 1'd1;
			end
		else num <= num;
		
	always @(posedge clk or negedge rst_n)
		if (!rst_n)
			begin 
				number <= 4'd0;
			end
		else 
			begin	
				number <= num;
			end
endmodule