始终块(组合)【Always blocks(combinational)】
答案:
Always blocks (clocked)
答案:
module top_module(
input clk,
input a,
input b,
output wire out_assign,
output reg out_always_comb,
output reg out_always_ff );
assign out_assign=a^b;
always@(*)
begin
out_always_comb=a^b;
end
always@(posedge clk)
begin
out_always_ff<=a^b;
end
endmodule
注意:
^代表或非
时序逻辑使用非阻塞语句<=(并行执行)在同一时间下一起运行,所以是时序
组合逻辑使用阻塞语句=(按顺序执行)
lf statement
答案:
module top_module(
input a,
input b,
input sel_b1,
input sel_b2,
output wire out_assign,
output reg out_always );
always@(*)
begin
if(sel_b1==1'b1&sel_b2==1'b1)
begin
out_always=b;
end
else
begin
out_always=a;
end
end
assign out_assign=(sel_b1==1'b1&sel_b2==1'b1)?b:a;
endmodule
lf statement latches
Case statement
答案:
module top_module (
input [2:0] sel,
input [3:0] data0,
input [3:0] data1,
input [3:0] data2,
input [3:0] data3,
input [3:0] data4,
input [3:0] data5,
output reg [3:0] out );//
always@(*) begin // This is a combinational circuit
case(sel)
0:out=data0;
1:out=data1;
2:out=data2;
3:out=data3;
4:out=data4;
5:out=data5;
default: out = 0; // 可替换为 out <= 0;
endcase
end
endmodule
注意:
- 组合逻辑中 :优先使用
=
,保持代码清晰性(显式表示顺序逻辑)。 - 时序逻辑中 :始终使用
<=
,避免竞争条件。 - 团队协作时 :统一赋值风格,减少潜在错误。
Priority encoder
答案:
// synthesis verilog_input_version verilog_2001
module top_module (
input [3:0] in,
output reg [1:0] pos
);
always @(*) begin
case (in)
4'b0000: pos = 2'd0;
4'b0001: pos = 2'd0;
4'b0010: pos = 2'd1;
4'b0011: pos = 2'd0;
4'b0100: pos = 2'd2;
4'b0101: pos = 2'd0;
4'b0110: pos = 2'd1;
4'b0111: pos = 2'd0;
4'b1000: pos = 2'd3;
4'b1001: pos = 2'd0;
4'b1010: pos = 2'd1;
4'b1011: pos = 2'd0;
4'b1100: pos = 2'd2;
4'b1101: pos = 2'd0;
4'b1110: pos = 2'd1;
4'b1111: pos = 2'd0;
default: pos = 2'd0; // 可选,因为上面已经覆盖了所有情况
endcase
end
endmodule
很蠢的枚举方法,暂且不知道其他方法怎么写