题目2:设计一个表决器
1、设计方案
输入peolpe_cnt为参与表决的人数,每一位bit表示一人,低位不赞成,高位赞成,输出is_or_not表示表决是否通过,低位不通过,高位通过。使用两个寄存器,cnt_is和cnt_not表示赞成和不赞成的人的个数,如果cnt_is>cnt_not则表示通过,反之则表示不通过。
2、程序代码
`timescale 1ns/1ns
module decision(
input i_clk,
input i_rst,
input [14:0]peolpe_cnt,
output reg is_or_not
);
reg [3:0]cnt_is;
reg [3:0]cnt_not;
integer i;
always@(*)begin
if(i_rst==1'b1)begin
cnt_is = 'd0;
cnt_not = 'd0;
end
else begin
for(i=0;i<15;i=i+1)begin
if(peolpe_cnt[i])begin
cnt_is = cnt_is+1;
cnt_not = cnt_not;end
else begin
cnt_not=cnt_not+1;
cnt_is = cnt_is;end
end
if(cnt_is>cnt_not)
is_or_not = 1'b1;
else
is_or_not=1'b0;
end
end
endmodule
3、仿真测试
`timescale 1ns/1ns
module decision_tb();
reg i_clk;
reg i_rst;
reg [14:0]peolpe_cnt;
wire is_or_not;
decision decision(
.i_clk(i_clk),
.i_rst(i_rst),
.peolpe_cnt(peolpe_cnt),
.is_or_not(is_or_not)
);
always #50 i_clk = ~i_clk;
initial begin
i_clk = 0;
i_rst = 1;
#200 i_rst = 0;
peolpe_cnt = 15'b111101000000000;
#100;
peolpe_cnt = 15'b000101010011111;
end
endmodule
4、结果分析
输入peolpe_cnt = 15'b111101000000000; 1的个数为5个,表示5个人赞成,10个人不赞成,则最终不通过,输出is_or_not为0,
输入peolpe_cnt = 15'b000101010011111; 1的个数为8个,表示8个人赞成,7个人不赞成,则最终通过,输出is_or_not为1,