If Statement
CoddyのVerilogジャーニー「基礎」セクションの一部。レッスン 52/90。
if 文は、condition が true の場合にのみコードを実行する意思決定ブロックです。if 文は condition をチェックします。
If the condition is true (1), the code inside executes. If the condition is false (0), the code is skipped.
構文:
if (condition) begin
// condition が true のときにコードが実行される
end簡単な例
if (reset) begin
count = 0;
endこの例では:
beginとendは、コードブロックの開始と終了を示すために使用されます
resetが 1(true)の場合、beginとendの内部のコードが実行されます →countは 0 になりますresetが 0(false)の場合、内部のコードはスキップされます → 何も起こりません
begin と end は、他のプログラミング言語における波かっこ { } と同じように機能します。これらはステートメントをまとめ、どのコードが if 条件に属するのかを Verilog が認識できるようにします。ここではステートメントが 1 つしかありませんが、一貫性を保つために begin と end を使用するのは、依然として良い習慣です。
Alwaysブロック内のif文
always @(posedge clk) begin
if (reset)
count <= 0;
end注: 1つの文の場合、begin と end は省略できます。たとえば、上記の always ブロックでは文が1つしかないため、if の後に begin/end は必要ありません。
条件には任意の式を使用できる
if (a > b) begin
max = a;
end
if (a && b) begin
out = 1;
end
if (data == 8'hFF) begin
match = 1;
end重要なルール
| ルール | 説明 |
|---|---|
| condition は任意の式にできる | 0 以外(かつ既知)の値は true として扱われ、0 は false として扱われる |
begin / end は複数の statement に必要 | 他の言語における { } と同様 |
begin/end がない場合、続くのは 1 つの statement のみ | 次の行だけ |
チャレンジ
行うこと:
- これを動作させるために、不足している
if文を追加してください。
enableが1のとき、outはa & bと等しくなる必要がありますenableが0のとき、outは0のまま(変更されない)である必要があります
スターターコードは out = 0 を初期化し、両方のケースをテストします。
自分で試してみよう
module if_challenge;
reg a, b, enable;
reg out = 0;
initial begin
a = 1;
b = 1;
// テストケース 1: enable = 1
enable = 1;
// TODO: if文を追加 (out = a & b)
$display("enable=1: out = %d (should be 1)", out);
// テストケース 2: enable = 0
enable = 0;
out = 0;
// TODO: out は 0 のままであるべき
$display("enable=0: out = %d (should be 0)", out);
$finish;
end
endmoduleこのレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
基礎のすべてのレッスン
4Operators Part 1
Arithmetic OperatorsModulo OperatorComparison OperatorsRecap - Simple MathBitwise Operators7Assign And Gates
Continuous AssignmentAssign With OperatorsBuilt In Gate PrimitivesAND OR NOT GatesXOR XNOR GatesRecap - Logic Gate Circuit10Decision Making
If StatementIf - ElseRecap - Simple ComparatorCase StatementCasex And CasezRecap - ALU Design5Operators Part 2
Logical OperatorsReduction OperatorsShift OperatorsConcatenation OperatorConditional OperatorRecap - Operator Challenge3Number System
Binary RepresentationSized NumbersUnsized NumbersNegative NumbersSpecial Values X And ZRecap - Number Formats6Modules
Module StructureInput And Output PortsInout PortsModule InstantiationPort Mapping By NamePort Mapping By OrderRecap - Build A Module9Procedural Blocks
Always BlockInitial BlockSensitivity ListBlocking AssignmentNon Blocking AssignmentRecap - Always vs Initial15Traffic Light Controller
Defining The StatesState Machine Logic自分で練習してみよう: Verilogオンラインコンパイラ