专栏前言
本专栏的内容主要是记录本人学习Verilog过程中的一些知识点,刷题网站用的是牛客网
分析
1、在硬件中进行乘除法运算是比较消耗资源的一种方法,想要在不影响延迟并尽量减少资源消耗,必须从硬件的特点上进行设计。根据寄存器的原理,由于是二进制,所以进位和退位为x2或者/2,同样除7可以使用进位3然后减去本身的做法,这样就将乘除法运算转化为位运算,这是一种比较简单的整数运算处理。
2、 需要给出一个计数器的状态机,注意d输入不是随时有效的,只有在cnt计数为0的那个时钟沿,d输入有效,因此需要设计一个寄存器din,在cnt为0时候锁存d的值
`timescale 1ns/1ns
module multi_sel(
input [7:0]d ,
input clk,
input rst,
output reg input_grant,
output reg [10:0]out
);
//*************code***********//
reg [1:0] cnt ;
reg [7:0] din ;
always @ (posedge clk or negedge rst) begin
if (~rst) begin
cnt <= 0 ;
out <= 0 ;
input_grant <= 0 ;
din <= 0 ;
end
else begin
cnt <= (cnt + 1) % 4 ; // cnt <= cnt + 1 由于是2位的寄存器 溢出后自动清0 两种写法皆可
case (cnt)
0 : begin
din <= d ;
input_grant <= 1 ;
out <= d ;
end
1 : begin
input_grant <= 0 ;
out <= (din << 2) - din ;
end
2 : begin
input_grant <= 0 ;
out <= (din << 3) - din ;
end
3 : begin
input_grant <= 0 ;
out <= din << 3 ;
end
endcase
end
end
//*************code***********//
endmodule
Testbench
`timescale 1ns/1ns
module testbench();
reg clk = 0 ;
reg rst = 0 ;
reg [7:0] d ;
wire [10:0] out ;
wire input_grant ;
always #5 clk = ~clk ;
// Create clock with period=10
// A testbench
initial begin
# 10 ;
rst = 1 ;
# 200 ;
end
initial begin
d = 143 ;
# 40 d = 7 ;
# 50 d = 6 ;
# 10 d = 128 ;
# 10 d = 129 ;
# 60 $finish ;
end
multi_sel u1(
.clk(clk),
.d(d),
.rst(rst),
.out(out),
.input_grant(input_grant)
);
//end
initial begin
$dumpfile("out.vcd");
// This will dump all signal, which may not be useful
//$dumpvars;
// dumping only this module
//$dumpvars(1, testbench);
// dumping only these variable
// the first number (level) is actually useless
$dumpvars(0, testbench);
end
endmodule