有限狀態機是Verilog中十分基本也是十分重要的知識。本文對有限狀態機作了一個簡單介紹。ide
1.狀態機三要素編碼
有限狀態機具備三個要素:狀態跳轉、跳轉判斷、狀態操做;spa
1)狀態跳轉:現態跳轉到次態;設計
2)跳轉判斷:狀態跳轉的判斷條件;code
3)狀態操做:狀態對應的操做;blog
2.狀態機的實現方式event
1)一段式:狀態機三要素集成於一個 always 塊中。class
1 always@(posedge clk or negedge rst_n) 2 begin 3 if(!rst_n)begin 4 state <= 2'b00; 5 Qout <= 1'b0; 6 end 7 else case(state) 8 2'b00: begin 9 if(A)begin 10 state <= 2'b01; 11 Qout <= 1'b1; 12 end 13 else begin 14 state <= 2'b00; 15 Qout <= 1'b0; 16 end 17 end 18 2'b01: begin 19 if(!A)begin 20 state <= 2'b00; 21 Qout <= 1'b0; 22 end 23 else begin 24 state <= 2'b01; 25 Qout <= 1'b1; 26 end 27 end 28 default:; 29 endcase 30 end
2)二段式:狀態機三要素分別設計於兩個 always 塊。cli
1 always@(posedge clk or negedge rst_n) 2 begin 3 if(!rst_n) 4 state <= 2'b00; 5 else case(state) 6 2'b00: begin 7 if(A) 8 state <= 2'b01; 9 else 10 state <= 2'b00; 11 end 12 2'b01: begin 13 if(!A) 14 state <= 2'b00; 15 else 16 state <= 2'b01; 17 end 18 default:; 19 endcase 20 end 21 22 always@(posedge clk or negedge rst_n) 23 begin 24 if(!rst_n) 25 Qout <= 1'b0; 26 else case(state) 27 2'b00: Qout <= 1'b0; 28 2'b01: Qout <= 1'b1; 29 default:; 30 endcase 31 end
3)三段式:狀態機三要素分別於三個 always 塊。sed
1 always@(posedge clk or negedge rst_n)//狀態跳轉 2 begin 3 if(!rst_n) 4 current_state <= 2'b00; //復位 5 else 6 current_state <= next_state//在時鐘上升沿刷新現狀態 7 end 8 9 always@(current_state) //跳轉判斷 10 begin 11 case(current_state) 12 2'b00:begin 13 if(A) 14 next_state = 2'b01; 15 else 16 next_state = 2'b00; 17 end 18 2'b01:begin 19 if(!A) 20 next_state = 2'b00; 21 else 22 next_state = 2'b01; 23 end 24 default:; 25 end 26 27 always @ (*) //狀態操做 28 begin 29 case(current_state) 30 2'b00:Qout <= 1'b0; 31 2'b01:Qout <= 1'b1; 32 default:; 33 endcase 34 end
3.狀態機設計要求
1)根據設計需求選擇合適的風格;
2)case語句中都應加入default語句;
3)巧加DFF中繼,提升可靠性;
4)課採用獨熱編碼、格雷碼設計狀態;
5)記得采用全局復位;