天天看点

HDLBits Day16 one-hot encoding

The following is the state transition table for a Moore state machine with one input, one output, and four states. Use the following one-hot state encoding: A=4’b0001, B=4’b0010, C=4’b0100, D=4’b1000.

HDLBits Day16 one-hot encoding

状态转移。什么时候next_state是A呢?

从表中可以很容易看出,当前state=A&in=0时,或者state=C&in=0时,next_state=A。那么我门要判断当前state是不是等于A。如果不用独热码,我们需要判断四位,在组合逻辑中,不仅需要更多的逻辑资源,还有可能因为传输路径远近的原因出现错误。而采用独热码以后,我们只需要判断一位就可以了。

eg: parameter A=0, B=1, C=2, D=3;

assign next_state[A] =state[A]&(~in) | state[C]&(~in);

整体代码:

module top_module(
    input in,
    input [3:0] state,
    output [3:0] next_state,
    output out); //

    parameter A=0, B=1, C=2, D=3;

    // State transition logic: Derive an equation for each state flip-flop.
    assign next_state[A] =state[A]&(~in) | state[C]&(~in);
    assign next_state[B] = state[A]&(in) | state[B]&(in)| state[D]&(in);
    assign next_state[C] = state[B]&(~in) | state[D]&(~in);
    assign next_state[D] = state[C]&(in);

    // Output logic: 
    assign out = (state[3] == 1'b1);

endmodule
           

注意在最后out输出时,也是仅判断state[D]这一位即可。(判断四位state==4’b1000还真出现错误了)。

HDLBits Day16 one-hot encoding
module top_module(
    input clk,
    input in,
    input areset,
    output out); //、
    parameter A=0,B=1,C=2,D=3;
    reg [3:0] state;
    wire [3:0] next_state;


    always@(posedge clk or posedge areset) begin 
        if(areset)
            state <=4'b0001;
    else state <= next_state;
    end
   
    assign next_state[A] =state[A]&(~in) | state[C]&(~in);
    assign next_state[B] = state[A]&(in) | state[B]&(in)| state[D]&(in);
    assign next_state[C] = state[B]&(~in) | state[D]&(~in);
    assign next_state[D] = state[C]&(in);
        
   assign out = (state[3] == 1'b1);

endmodule
           

用独热码而不用写出4‘b1000,4’b0100…不用给每一状态起名字,只用current_state,next_state即可。