1.原理
2.代码
2.1 complex_fsm.v
module complex_fsm(input wire sys_clk ,input wire sys_rst_n ,input wire pi_money_half ,input wire pi_money_one ,output reg po_cola ,output reg po_money
);parameter IDLE= 5'b00001,HALF= 5'b00010,ONE= 5'b00100,ONE_HALF= 5'b01000,TWO= 5'b10000;wire [1:0] pi_money;
reg [4:0] state;assign pi_money={pi_money_one,pi_money_half};always@(posedge sys_clk or negedge sys_rst_n)if (sys_rst_n==1'b0)state <=IDLE;else case(state)IDLE: if(pi_money==2'b01)state<=HALF;else if(pi_money==2'b10)state<=ONE;elsestate<=IDLE;HALF: if(pi_money==2'b01)state<=ONE;else if(pi_money==2'b10)state<=ONE_HALF;elsestate<=HALF;ONE: if(pi_money==2'b01)state<=ONE_HALF;else if(pi_money==2'b10)state<=TWO;elsestate<=ONE;ONE_HALF:if(pi_money==2'b01)state<=TWO;else if(pi_money==2'b10)state<=IDLE;elsestate<=ONE_HALF;TWO: if(pi_money==2'b01)state<=IDLE;else if(pi_money==2'b10)state<=IDLE;elsestate<=IDLE;default:state<=IDLE;endcasealways@(posedge sys_clk or negedge sys_rst_n)if (sys_rst_n==1'b0)po_cola<=1'b0;else if(((state==ONE_HALF)&&(pi_money==2'b10))||((state==TWO)&&(pi_money==2'b01))||((state==TWO)&&(pi_money==2'b10)))po_cola<=1'b1;elsepo_cola<=1'b0;always@(posedge sys_clk or negedge sys_rst_n)if (sys_rst_n==1'b0)po_money<=1'b0;else if((state==TWO)&&(pi_money==2'b10))po_money<=1'b1;elsepo_money<=1'b0;endmodule
2.2 tb_complex_fsm.v
`timescale 1ns/1ns
module tb_complex_fsm();reg sys_clk;
reg sys_rst_n;
reg pi_money_half;
reg pi_money_one ;
reg random_money;wire po_cola ;
wire po_money ;initial beginsys_clk=1'b1;sys_rst_n<=1'b0;#20sys_rst_n<=1'b1;endalways #10 sys_clk=~sys_clk;always@(posedge sys_clk or negedge sys_rst_n)if (sys_rst_n==1'b0)random_money<=1'b0;else random_money<={$random}%2;always@(posedge sys_clk or negedge sys_rst_n)if (sys_rst_n==1'b0)pi_money_half<=1'b0;else pi_money_half<=random_money;always@(posedge sys_clk or negedge sys_rst_n)if (sys_rst_n==1'b0)pi_money_one<=1'b0;else pi_money_one<=~random_money;complex_fsm complex_fsm_inst(.sys_clk (sys_clk) ,.sys_rst_n (sys_rst_n),.pi_money_half (pi_money_half),.pi_money_one (pi_money_one),.po_cola (po_cola) ,.po_money (po_money)
);endmodule