举个简单点的例子,如下。
设计一个4bit的计数器,在记到最大值时输出一个信号
module counter_16 ( input clk, input rst_n, input cnt_in ,output reg cnt_out );
reg [3:0] cnt;
always @ (posedge clk or negedge rst_n) begin
if (~rst_n) cnt <= 4'b0;
else if (cnt_in) cnt <= cnt +1'b1;
else cnt <= cnt;
end
always @ (posedge clk or negedge rst_n) begin
if (~rst_n) cnt_out <= 1'b0;
else if (cnt_in && cnt == 4'b1111) cnt_out <= 1'b1;
else cnt_out <= 1'b0;
end
endmodule
这实际上设计了一个16进制计数器其中的一位,你可以例化多个相同模块,将低位的cnt_out连接到高位的cnt_in,级联成一个任意位数的16进制计数器。
module fsm//模5计数器
(input clk,clr,
output reg Z,
output reg[2:0] qout) ;
always @ (posedge c1k, posedge clr)
//此过程定义状态转换
begin
if(clr) qout<=0;
//异步复位
else case (qout)
3'b000: qout<=3'b001;
3'b001: qout<=3'b010;
3'b010: qout<=3'b011;
3'b011: qout<=3'b100;
3'b100: qout<=3' b000;
default: qout<=3'b000;
/*default语句*/
endcase
end
always e (qout)
/*此过程产生输出逻辑*/
begin case (qout)
3'b100: z=1 'bl;
default:z=1 'b0;
endcase
end
endmodule