FSM自动售货机 verilog 实现及 code 细节讲解

  • 2021 年 8 月 17 日
  • 筆記

1.题目: 饮料1.5 元, 可投入硬币1 元 0.5 元,输出饮料 零钱

2. 画出状态机。

3.仿真结果:coin=1 –> 0.5 元 coin=2–>1元

4.关键代码分析:

本次设计采用了5个状态,输出结果采用寄存器输出,确保输出后稳定可靠,采用的是case(nx_state )语句输出判断的结果,提前一个周期判断,就可以确保输出与当前状态想要的条件到达时的输出条件一直。如上在S3 状态时,直接输出10,S4状态时,直接输出11. 同样的功能还可以用assign 语句,assign {drink_out,change}=(state==S3)?10:00; 但这是组合逻辑输出形式。对于后续模块时序上不太友好。

5.完整代码:

 
module auto_machine(
input clk,rst_n,
input [1:0] coin, 
output reg drink_out, change
);//coin =0  no coin ,coin =1--->0.5 yuan  coin =2---> 1 yuan
reg [2:0] state,nx_state;

parameter [2:0] IDLE=3'd0,S1=3'd1,S2=3'd2 ,S3=3'd3,S4=3'd4;

always @(posedge clk or negedge rst_n)
if(!rst_n)
state<=IDLE;
else
state<=nx_state;

always @(*) begin 
nx_state=IDLE;
case(state)
IDLE: if(coin==2'd1)    nx_state=S1;else if(coin==2'd2)
        nx_state=S2; else nx_state=IDLE;
S1:   if(coin==2'd1)    nx_state=S2;else if(coin==2'd2)
        nx_state=S3; else nx_state=S1;
         
S2:   if(coin==2'd1)    nx_state=S3;else if(coin==2'd2)
        nx_state=S4; else nx_state=S2;
S3:     nx_state=IDLE;
S4:     nx_state=IDLE;
default:nx_state=IDLE;
endcase

end

always @(posedge clk or negedge rst_n)
if(!rst_n)
{drink_out, change}<='b0;
else
case(nx_state)
S3: {drink_out, change}<=10;
S4: {drink_out, change}<=11;
endcase



endmodule

6.测试代码;

`timescale 1ns/1ps

module auto_tb();
reg rst_n,clk;
 
 reg [1:0]coin;
 wire drink_out, change;
initial begin
rst_n=0;
clk=0;
coin=2'd0;
#100
rst_n=1;
#10
coin=2'd1;
#20
coin=2'd0;
#20
coin=2'd1;
#20
coin=2'd1;  //have drink_out
#20
coin=2'd1;
#20
coin=2'd2;  //have drink_out
#20
coin=2'd2;
#20
coin=2'd2;      //have drink_out and change out
#20
coin=2'd2;



end

always #10 clk=~clk;

 auto_machine auto2(
 clk,rst_n,
 coin, 
 drink_out, change
);



endmodule

tb