1.组合逻辑的always块表达
module top_module(
input a,
input b,
output wire out_assign,
output reg out_alwaysblock
);
assign out_assign = a & b;
always @ (*)
out_alwaysblock <= a & b;
endmodule
2.有时钟控制的always块
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 @ (*)
out_always_comb <= a ^ b;
always @ (posedge clk)
out_always_ff <= a ^ b;
endmodule
3.if语句
用if语句和assign语句实现2-1选择器
module top_module(
input a,
input b,
input sel_b1,
input sel_b2,
output wire out_assign,
output reg out_always );
assign out_assign = (sel_b1 & sel_b2) == 1'b1 ? b : a;
always @ (*)
if(sel_b1 & sel_b2 == 1'b1) begin
out_always <= b;
end
else begin
out_always <= a;
end
endmodule
4.避免造成锁存器(缺少else情况)
在计算机过热时关闭计算机,在到达目的地或需要加油时停止驾驶。
module top_module (
input cpu_overheated,
output reg shut_off_computer,
input arrived,
input gas_tank_empty,
output reg keep_driving );
always @(*) begin
if (cpu_overheated)
shut_off_computer = 1;
else
shut_off_computer = 0;
end
always @(*) begin
if (~arrived)
keep_driving = ~gas_tank_empty;
else
keep_driving = 0;
end
endmodule
5.case语句
实现6-1多路选择器,当 sel 介于0和5之间时,选择相应的数据输入。否则,输出0。数据输入和输出均为4位宽。
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)
3'b000: out = data0;
3'b001: out = data1;
3'b010: out = data2;
3'b011: out = data3;
3'b100: out = data4;
3'b101: out = data5;
default: out = 0;
endcase
end
endmodule
6.Priority encoder
构建4位优先级编码器。对于此问题,如果输入位都不高(即输入为零),则输出为零。
// synthesis verilog_input_version verilog_2001
module top_module (
input [3:0] in,
output reg [1:0] pos );
always @(*) begin
casex (in[3:0]) //casex或者casez
4'bxxx1: pos = 0; // in[3:1] can be anything
4'bxx10: pos = 1;
4'bx100: pos = 2;
4'b1000: pos = 3;
default: pos = 0;
endcase
end
endmodule
7.Always casez
输入8位构建优先级编码器。给定一个8位向量,输出应输出向量中第一个。例如,输入 8’b10010000 应输出 3’d4,因为 bit[4]是第一个高位。
// synthesis verilog_input_version verilog_2001
module top_module (
input [7:0] in,
output reg [2:0] pos );
always @ (*) begin
casez(in[7:0])
8'bzzzz_zzz1 : pos = 3'b000;
8'bzzzz_zz10 : pos = 3'b001;
8'bzzzz_z100 : pos = 3'b010;
8'bzzzz_1000 : pos = 3'b011;
8'bzzz1_0000 : pos = 3'b100;
8'bzz10_0000 : pos = 3'b101;
8'bz100_0000 : pos = 3'b110;
8'b1000_0000 : pos = 3'b111;
default : pos = 3'b000;
endcase
end
endmodule
8.Always nolatches
为避免创建锁存器,必须在所有可能的条件下为所有输出分配一个值。仅仅有一个默认情况是不够的,您必须为所有四种情况和默认情况下的所有四个输出分配一个值,这可能涉及大量不必要的输入。
// synthesis verilog_input_version verilog_2001
module top_module (
input [15:0] scancode,
output reg left,
output reg down,
output reg right,
output reg up );
always @(*) begin
up = 1'b0; down = 1'b0; left = 1'b0; right = 1'b0;
case(scancode)
16'he06b : left = 1'b1;
16'he072 : down = 1'b1;
16'he074 : right = 1'b1;
16'he075 : up = 1'b1;
default : ; //default中可以没有
endcase
end
endmodule