我对 Verilog 编程完全陌生,我不明白在哪里初始化reg变量?
让我们看一下以下片段: 编辑: 合成时发出警告
module test (
output LED0
);
reg led = 1'b1;
assign LED0 = led;
endmodule
Run Code Online (Sandbox Code Playgroud)
或者
module test (
output LED0
);
reg led;
initial begin
reg led <= 1'b1;
end
assign LED0 = led;
endmodule
Run Code Online (Sandbox Code Playgroud)
给我:使用 led 的初始值,因为它从未在行中分配: reg led = 1'b1;
reg类型是否仅在 always@ 块中分配?
另一个例子:
module fourBitCounter
(input clk,
output [3:0]counter
);
wire clk;
initial begin
reg[3:0] counter = 4'b1;
end
always@ (posedge clk) begin
if(counter > 15)
counter <= 0;
else
counter <= counter + 1;
end endmodule
Run Code Online (Sandbox Code Playgroud)
此处 reg 的初始值为 0,但我之前已将其设置为 1... 有什么问题?谢谢!
reg 类型是否只在 always@ 块中分配?
不,reg可以在always块和initial块中分配类型(加上task和function但我会在这个问题的范围内跳过它们)
对于您的fourBitCounter,reg[3:0] counter在initial块中声明的会创建一个局部变量,也称为counter只能在创建它的块的范围内访问。您需要删除reg[3:0]初始块中的 ,以便分配按预期应用counter。但它仍然不起作用,因为您声明counter为推断的连线类型并且always/initial块无法分配连线。
counter被声明为 4 位推断线的输出(output [3:0] counter是 的同义词output wire [3:0] counter)。由于counter在always块和initial块中分配,因此它需要是一种reg类型。因此它应该被声明为output reg [3:0] counter.
此外,您声明clk为输入和本地连线,它不能同时存在。端口可以在本地访问,没有理由将它们重新声明为本地网络。
仅供参考:对于 4 位值,15+1 等于 0,因为没有任何东西可以存储 MSB。
module fourBitCounter (
input clk,
output reg [3:0] counter // 'output reg', not 'output'
);
//wire clk; // do not do this, clk is an input
initial begin
counter = 4'b1; // no 'reg' here
end
always @(posedge clk) begin
if(counter > 15) // this will never evaluate as true with counter declared as 4-bit
counter <= 0;
else
counter <= counter + 1;
end
endmoduleRun Code Online (Sandbox Code Playgroud)
对于 Verilog,assign语句只能应用于网络类型(例如wire)。这是合法的:
module test ( output LED0 ); // LED0 is an inferred wire
assign LED0 = 1'b1;
endmodule
Run Code Online (Sandbox Code Playgroud)
这是非法的:
module test ( output reg LED0 ); // Explicit reg
assign LED0 = 1'b1; // illegal, assign on a reg
endmodule
Run Code Online (Sandbox Code Playgroud)