{"id":167,"date":"2015-10-14T09:55:07","date_gmt":"2015-10-14T16:55:07","guid":{"rendered":"http:\/\/www.verilogpro.com\/?p=167"},"modified":"2022-06-27T00:42:19","modified_gmt":"2022-06-27T07:42:19","slug":"systemverilog-one-hot-state-machine","status":"publish","type":"post","link":"https:\/\/www.verilogpro.com\/systemverilog-one-hot-state-machine\/","title":{"rendered":"One-hot State Machine in SystemVerilog – Reverse Case Statement"},"content":{"rendered":"\n

Finite state machine (FSM) is one of the first topics taught in any digital design course, yet coding one is not as easy as first meets the eye. There are Moore and Mealy state machines, encoded and one-hot state encoding, one or two or three always<\/b> block coding styles. Recently I was reviewing a coworker’s RTL code and came across a SystemVerilog one-hot state machine coding style that I was not familiar with. Needless to say, it became a mini research topic resulting in this blog post.<\/p>\n\n\n\n

When coding state machines in Verilog or SystemVerilog, there are a few general guidelines that can apply to any state machine:<\/p>\n\n\n\n

  1. If coding in Verilog, use parameters to define state encodings instead of ‘define<\/b> macro definition. Verilog ‘define<\/b> macros have global scope; a macro defined in one module can easily be redefined by a macro with the same name in a different module compiled later, leading to macro redefinition warnings and unexpected bugs.<\/li>
  2. If coding in SystemVerilog, use enumerated types to define state encodings.<\/li>
  3. Always define a parameter or enumerated type value for each state so you don’t leave it to the synthesis tool to choose a value for you. Otherwise it can make for a very difficult ECO when it comes time to reverse engineer the gate level netlist.<\/li>
  4. Make curr_state<\/i> and next_state<\/i> declarations right after the parameter or enumerated type assignments. This is simply clean coding style.<\/li>
  5. Code all sequential always block using nonblocking assignments (<=). This helps guard against simulation race conditions.<\/li>
  6. Code all combinational always block using blocking assignments (=). This helps guard against simulation race conditions.<\/li><\/ol>\n\n\n\n

    SystemVerilog enumerated types are especially useful for coding state machines. An example of using an enumerated type as the state variable is shown below.<\/p>\n\n\n\n

    typedef enum {\n  IDLE   = 2'b00,\n  ACTIVE = 2'b01,\n  DONE   = 2'b10,\n  XX     = 'x\n} state_t;\nstate_t curr_state, next_state;<\/pre>\n\n\n\n