DigitalSystemDesign12011/6/21ComputerFacultyofGuangdongUniversityofTechnology例:用三进程状态机实现一个简单自动售货机控制电路,电路框图如下。该电路有两个投币口(1元和5角),商品2元一件,不设找零。In[0]表示投入5角,In[1]表示投入1元,Out表示是否提供货品。自动售货机In[0]In[1]ClkResetOut自动售货机顶层结构框图DigitalSystemDesign22011/6/21ComputerFacultyofGuangdongUniversityofTechnology根据题意,可分析出状态机的状态包括:S0(00001):初始状态,未投币或已取商品S1(00010):投币5角S2(00100):投币1元S3(01000):投币1.5元S4(10000):投币2元或以上用独热码表示状态编码,如上所示。相应状态转换图如下(按Moore状态机设计)。DigitalSystemDesign32011/6/21ComputerFacultyofGuangdongUniversityofTechnologyxx/101/010/010/001/001/0S1S0S4S2Reset自动售货机状态转换图10/0S301/0x1/0DigitalSystemDesign42011/6/21ComputerFacultyofGuangdongUniversityofTechnology设计代码第一个Always块:状态转移。`timescale1ns/100psmodulesaler_3always(Reset,Clk,In,Out);inputClk,Reset;input[1:0]In;outputOut;regOut;reg[4:0]state,next_state;parameterS0=5'b00001,S1=5'b00010,S2=5'b00100,S3=5'b01000,S4=5'b10000;always@(posedgeClkorposedgeReset)beginif(Reset)state=S0;elsestate=next_state;endDigitalSystemDesign52011/6/21ComputerFacultyofGuangdongUniversityofTechnology第二个Always块:状态转移的组合逻辑条件判断always@(stateorIn)begincase(state)S0:beginif(In[1])next_state=S2;elseif(In[0])next_state=S1;elsenext_state=S0;endS1:beginif(In[1])next_state=S3;elseif(In[0])next_state=S2;elsenext_state=S1;endS2:beginif(In[1])next_state=S4;elseif(In[0])next_state=S3;elsenext_state=S2;endS3:beginif(In[0]|In[1])next_state=S4;elsenext_state=S3;endS4:beginnext_state=S0;enddefault:next_state=S0;endcaseendDigitalSystemDesign62011/6/21ComputerFacultyofGuangdongUniversityofTechnology第三个Always块:输出组合逻辑always@(state)begincase(state)S0:beginOut=0;endS1:beginOut=0;endS2:beginOut=0;endS3:beginOut=0;endS4:beginOut=1;enddefault:Out=0;endcaseendendmoduleDigitalSystemDesign72011/6/21ComputerFacultyofGuangdongUniversityofTechnology测试平台代码`timescale1ns/1nsmoduletestbench_saler;regclk,reset;reg[1:0]in;wireout;parameterDELY=20;saler_3alwaystb(.Clk(clk),.Reset(reset),.In(in),.Out(out));always#(DELY/2)clk=~clk;initialbeginclk=0;reset=0;#20reset=1;#20reset=0;endinitialbeginin=0;repeat(20)#20in=$random;endinitial#400$finish;endmoduleDigitalSystemDesign82011/6/21ComputerFacultyofGuangdongUniversityofTechnology功能仿真结果DigitalSystemDesign92011/6/21ComputerFacultyofGuangdongUniversityofTechnology综合结果