题目:
Suppose you’re building a circuit to process scancodes from a PS/2 keyboard for a game. Given the last two bytes of scancodes received, you need to indicate whether one of the arrow keys on the keyboard have been pressed. This involves a fairly simple mapping, which can be implemented as a case statement (or if-elseif) with four cases.
解题:
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;
endcase
end
endmodule
结果正确:
注意点:
为避免产生锁存,必须在所有可能条件下为所有输出分配一个值(另请参阅always_if2).仅仅有一个默认案例是不够的。在所有四种情况和默认情况下,必须为所有四个输出分配一个值。这可能涉及大量不必要的键入。解决此问题的一种简单方法是在 case 语句之前为输出分配一个“默认值”:
always @(*) begin
up = 1'b0; down = 1'b0; left = 1'b0; right = 1'b0;
case (scancode)
... // Set to 1 as necessary.
endcase
end
这种代码样式可确保在所有可能的情况下都为输出分配一个值(0),除非 case 语句覆盖赋值。这也意味着 default: case 项变得不必要。