牛客网Verilog刷题------VL51
题目
请编写一个十六进制计数器模块,计数器输出信号递增每次到达0,给出指示信号zero,当置位信号set 有效时,将当前输出置为输入的数值set_num。模块的接口信号图如下:
模块的时序图如下:
输入输出描述:
信号 | 类型 | 输入/输出 | 位宽 | 描述 |
---|---|---|---|---|
clk | wire | Input | 1 | 系统时钟信号 |
rst_n | wire | Input | 1 | 异步复位信号,低电平有效 |
set | wire | Input | 1 | 置位指示信号,当该信号有效时,表示将输出信号强制置为set_num |
set_num | wire | Input | 4 | 4比特信号,当set信号有效时,将该信号的数字赋予输出信号number |
zero | reg | Output | 1 | 过零指示信号,当number计数到0时,该信号为1,其余时刻为0 |
number | reg | Output | 4 | 4比特位宽,表示计数器的当前读数 |
答案
c
`timescale 1ns/1ns
module count_module(
input clk,
input rst_n,
input set,
input [3:0] set_num,
output reg [3:0]number,
output reg zero
);
reg [3:0] r_number;
always @(posedge clk or negedge rst_n)
if(!rst_n)
r_number <= 4'd0;
else if(set)
r_number <= set_num;
else if(r_number == 4'd15)
r_number <= 4'd0;
else
r_number <= r_number + 1'b1;
always @(posedge clk or negedge rst_n)
if(!rst_n)
zero <= 1'b0;
else if(r_number=='d0)
zero <= 1'b1;
else
zero <= 1'b0;
always @(posedge clk or negedge rst_n)
if(!rst_n)
number <= 'd0;
else
number <= r_number;
endmodule