1.if statement latches
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 @(arrived or gas_tank_empty) begin
if (~arrived && ~gas_tank_empty)
keep_driving = 1;
else
keep_driving=0;
end
endmodule
2.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)
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
3.priority encoder
module top_module (
input [3:0] in,
output reg [1:0] pos );
always@(in) begin
case(in)
4'b0001: pos<=2'b00;
4'b0010: pos<=2'b01;
4'b0011: pos<=2'b00;
4'b0100: pos<=2'b10;
4'b0101: pos<=2'b00;
4'b0110: pos<=2'b01;
4'b0111: pos<=2'b00;
4'b1000: pos<=2'b11;
4'b1001: pos<=2'b00;
4'b1010: pos<=2'b01;
4'b1011: pos<=2'b00;
4'b1100: pos<=2'b10;
4'b1101: pos<=2'b00;
4'b1110: pos<=2'b01;
4'b1111: pos<=2'b00;
4'b0000: pos<=2'b00;
endcase
end
endmodule
4.priority encoder casez
module top_module (
input [7:0] in,
output reg [2:0] pos );
always@(in)
casez(in)
8'bzzzzzzz1: pos<=3'b000;
8'bzzzzzz10: pos<=3'b001;
8'bzzzzz100: pos<=3'b010;
8'bzzzz1000: pos<=3'b011;
8'bzzz10000: pos<=3'b100;
8'bzz100000: pos<=3'b101;
8'bz1000000: pos<=3'b110;
8'b10000000: pos<=3'b111;
default: pos<=3'b000;
endcase
endmodule
5.avoiding latches
module top_module (
input [15:0] scancode,
output reg left,
output reg down,
output reg right,
output reg up );
always@(scancode) begin
left<=1'b0;
down<=1'b0;
right<=1'b0;
up<=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:;
endcase
end
endmodule