要求:实现一个可乐机,投三颗币出一瓶可乐
分析:money有一个时钟周期高电平,相当于投币一颗,投三颗出一瓶可乐,所以应该是有三种状态
module state_1(
input wire sys_clk,
input wire rst_n,
input wire money,
output reg cole
);
parameter IDLE = 3'b001; //state状态表示采用独热码,相对节省组合电路,稍微浪费存储空间,(少状态用独热码,多状态可用格雷码)
parameter ONE = 3'b010;
parameter TWO = 3'b100;
reg [2:0] state;
always@(posedge sys_clk or negedge rst_n)
if (~rst_n)
state <= IDLE;
else case(state)
IDLE:
if (money==1'b1)
state <= ONE;
else
state <= IDLE;
ONE:
if (money==1'b1)
state <= TWO;
else
state <= ONE;
TWO:
if (money==1'b1)
state <= IDLE;
else
state <= TWO;
default : state <= IDLE; //别忘了
endcase
always @(posedge sys_clk or negedge rst_n) //将cole的判断写在case 语句中显得更加臃肿,还不如单独写一个always
if (~rst_n)
cole <=1'b0;
else if ((state == TWO) && (money == 1'b1)) //两个条件同时进行判断,如果只判断第一个,难道在状态two时一直出cole?
cole <= 1'b1;
else
cole <= 1'b0;
endmodule
module vtf_state_1;
// Inputs
reg sys_clk;
reg rst_n;
reg money;
// Outputs
wire cole;
wire [2:0]state=uut.state; //将实例化中的变量拿出来看
// Instantiate the Unit Under Test (UUT)
state_1 uut (
.sys_clk(sys_clk),
.rst_n(rst_n),
.money(money),
.cole(cole)
);
initial begin
// Initialize Inputs
sys_clk = 0;
rst_n = 0;
money = 0;
// Wait 100 ns for global reset to finish
#100;
rst_n <=1;
// Add stimulus here
end
always #10 sys_clk = ~sys_clk;
always #20 money ={$random}%2;
initial begin
$timeformat (-9,0,"ns",6);
$monitor ("@time %t: money=%b,state=%b, cole=%b ", $time,money,state,cole); //相当于打印
end
endmodule