2021年6月26日 星期六

HDLBits Simple FSM1 / Fsm1

 HDLBits Simple FSM1 / Fsm1

采用三段式的寫法來描述這個簡單的狀態機。三段式狀態機雖然代碼會長一些,但能夠更方便地修改,並更清晰地表達狀態機的跳變與輸出規則。
使用參數來表示每個狀態。


// Give state names and assignments. I'm lazy, so I like to use decimal numbers.
// It doesn't really matter what assignment is used, as long as they're unique.
parameter A=0, B=1;
reg state; // Ensure state and next are big enough to hold the state encoding.
reg next;


    // A finite state machine is usually coded in three parts:
    //  State transition logic
    //  State flip-flops


    //  Output logic
    // It is sometimes possible to combine one or more of these blobs of code
    // together, but be careful: Some blobs are combinational circuits, while some
    // are clocked (DFFs).


三段式分別指
狀態跳轉邏輯
狀態觸发器實現
輸出邏輯


狀態跳轉邏輯,根據輸入信號以及當前狀態確定狀態的次態。
// Combinational always block for state transition logic. Given the current state and inputs,
// what should be next state be?
// Combinational always block: Use blocking assignments.
  always@(*) begin
case (state)
A: next = in ? A : B;
B: next = in ? B : A;
endcase
    end


狀態觸发器實現,在時鐘邊沿實現狀態寄存器的跳變以及狀態覆位
// Edge-triggered always block (DFFs) for state flip-flops. Asynchronous reset.
    

    always @(posedge clk, posedge areset) begin
if (areset) state <= B; // Reset to state B
        else state <= next;  // Otherwise, cause the state to transition
    end


輸出邏輯,根據當前狀態實現輸出
// Combinational output logic. In this problem, an assign statement is the simplest.
// In more complex circuits, a combinational always block may be more suitable.

assign out = (state==B);




module top_module(
    input clk,
    input areset,    // Asynchronous reset to state B
    input in,
    output out);//  


    parameter A=0, B=1; 
    reg state, next_state;
    


    // This is a sequential always block
    always @(posedge clk, posedge areset) begin    
        // State flip-flops with asynchronous reset
    if (areset) 
           state<=B;
        else
           state<=next_state;    
    end


    always @(*) begin    // This is a combinational always block
        // State transition logic
        case(state)
            B: next_state= in? B:A;
            A: next_state= in? A:B;
        endcase
    end


    // Output logic
    // assign out = (state == ...);
    always@(*) begin
   case (state)
A: out = 1'b0;
B: out = 1'b1;
endcase
    end             
endmodule

沒有留言:

張貼留言

2024產專班 作業2 (純模擬)

2024產專班 作業2  (純模擬) 1) LED ON,OFF,TIMER,FLASH 模擬 (switch 控制) 2)RFID卡號模擬 (buttom  模擬RFID UID(不從ESP32) Node-Red 程式 [{"id":"d8886...