Electronic – Verilog Adding value in an always block. SIMPLE

fpgaverilog

module prizes(TESTSSD);
output reg [6:0]TESTSSD;
reg [1:0]equals; 

always @(*) begin
    equals = equals + 1;
    case (equals)
        0: TESTSSD = 7'b0000001;
        1: TESTSSD = 7'b1001111;
        2: TESTSSD = 7'b0010010;
        3: TESTSSD = 7'b0000110;
        4: TESTSSD = 7'b1001100;
        default:TESTSSD = 7'b0000000;
    endcase
end
endmodule

When I run the code above, I get a messed up looking 2 on the seven segment display; it is missing the middle part. What am I doing wrong?

Best Answer

always @(*) begin

This means whenever any variable that appears on a right-hand side in the block changes, run the block.

    equals = equals + 1;

This changes the variable equals.

So whenever equals changes, you increment equals. Which means equals changes, which means you increment it again, and so on.

So basically, equals just keeps incrementing as fast as the hardware can make it happen.

If you output this to a 7-segment display, you will just see the superposition of '0', '1', '2', and '3', flashing as quickly as the hardware can go. This will be much faster than your eye can follow. I don't know what it happens to look like, but if you say it looks like a '2', I believe you.

The usual way to do what you seem to want is to make equals increment only when something special happens, like the edge of a slow-ish clock (like maybe 5 Hz at most for the display to be meaningful to the human eye); or only when some special event happens that you're trying to count.

Edit

I should also add that, because of race conditions, if you implement this design in real hardware, it's likely that the output doesn't actually transition through all the states 0, 1, 2, 3, as expected, or that it doesn't do it in the order you expect.

For example if you're in the 2'b01 state, you expect to transition to 2'b10. But the signal to change bit 0 might propagate through more quickly than the signal to change bit 1, resulting in a glitch to the 2'b00 state. If that glitch lasts long enough, the circuit might go from there to the 2'b01 state again instead of to 2'b10. But that's just an example. What really happens depends on the transistor-level and wire-geometry level details of how the circuit is built.