Altera_Forum
Honored Contributor
14 years agois VHDL unsafe with state machine?
Typical VHDL state machine is to define a type that consist of states, then use that type in a signal. But if someone (not me, no way! ;-)) forget to put a reset state, the state machine continues to work starting from the first state declared in type. This is wrong! It should go to undefined state. But since the state definition does not include undefined state, it never goes there. Below is an example code.
type state_type is (S0, S1, S2, S3, STARTUPSTATE); signal currState, nextState : state_type; begin process(currState) begin case currState is when S0 => blah0; nextState <= findNextState(blah0); when S1 => blah1; nextState <= findNextState(blah1); when S2 => blah2; nextState <= findNextState(blah2); when S3 => blah3; nextState <= findNextState(blah3); when STARTUPSTATE => nextState <= findNextState(someCondition); when others => -- never goes here end case; end process; process(reset, clk) begin if reset='1' then -- currState <= STARTUPSTATE; somebody forgot this reset!!! elsif rising_edge(clk) then currState <= nextState; end if; end process; Note that the state machine starts at S0, not STARTUPSTATE as intended. One could argue that STARTUPSTATE should be the first item in state type, but that's not the point; the problem arose out of error, and VHDL did not flag it as "X". Also, that still doesn't fix the problem: after P&R, flop is not reset property, and one doesn't know what state the flop will take. But functional simulation will work just fine. It seems coding state machine like this is going to mask problems that may come up in hardware after P&R. One way to circumvent this is to use std_logic_vector to explicitly encode that states. But doing that means one has to binary code the states and more decoding is needed as opposed to more efficient methods such as one-hot. And doing one-hot in VHDL means if-else rather than case, which could incur unnecessary logic. If FPGA always take on some value, that might be fine. But flops without reset must take on undefined values upon power up until valid inputs (D + CK) are present. This becomes especially problematic for ASIC emulation where ASIC behaves differently than FPGA due to coding error that was masked by VHDL. So what are the options other than going to Verilog for safe coding of state machine in VHDL that will catch errors like this without explicitly specifying the state values? Thank you.