I am a beginner in Verilog, and I am trying to design a counter. My aim is to increment the count value whenever I press the switch sw
. But, I am getting a syntax error at the second if
:
else if (~sw & posedge clk)
The simulator did not provide any other details other than mentioning it is a syntax error. I am unable to understand the error. Please help.
module counter (clk,reset,led,sw);
input clk,reset,sw;
output [3:0] led;
reg [3:0] count;
integer temp = 0;
always @ (*)
if (~reset)
count <= 4'b0;
else if (~sw & posedge clk)
temp =1;
else
count <= count;
if (temp==1)
begin
count <= count +1;
temp =0;
end
else
count <= count;
assign led = count [3:0];
endmodule
-
\$\begingroup\$ What is the error? Also, you should use begin/end to group together what you want included in the in the always block. \$\endgroup\$Samuel– Samuel2013年10月18日 19:57:52 +00:00Commented Oct 18, 2013 at 19:57
2 Answers 2
The second 'if' statement is not part of the 'always' block. Try putting 'begin' and 'end' around the logic you want to group.
-
\$\begingroup\$ The 2nd
if
is part of thealways
block:if (~sw & posedge clk)
. But, the 3rdif
is not:if (temp==1)
. Usingbegin/end
is an improvement, but it does not solve the original syntax error. \$\endgroup\$toolic– toolic2023年06月06日 16:52:19 +00:00Commented Jun 6, 2023 at 16:52
else if (~sw & posedge clk)
It is illegal to use the posedge clk
event control inside the if
clause that way.
There are other syntax errors as well. The indentation you used is misleading. The if (temp==1)
statement and its else
clause are not part of the always
block as your indentation would indicate. It is illegal to have them outside of a procedure block (like an always
block). Perhaps you intended them to be enclosed within begin/end
keywords under the always
block.
Regardless of the syntax errors, that is an incorrect way to model a counter in Verilog. Here is a much simplified version of your code which has no syntax errors:
module counter (
input clk, reset, sw,
output [3:0] led
);
reg [3:0] count;
always @(posedge clk) begin
if (~reset) begin
count <= 4'b0;
end else if (sw) begin
count <= count + 1;
end
end
assign led = count;
endmodule
This code uses an active-low, synchronous reset signal. The counter is enabled only when sw
is high. The counter will automatically roll over to 0 if sw
remains high for 16 clock cycles.
Explore related questions
See similar questions with these tags.