题解 | #自动售卖机#
自动售卖机
https://www.nowcoder.com/practice/487953e6d3e3434988e0dd6960b6c9f8
`timescale 1ns/1ns
module sale(
input clk ,
input rst_n ,
input sel ,//sel=0,5$dranks,sel=1,10&=$drinks
input [1:0] din ,//din=1,input 5$,din=2,input 10$
output reg [1:0] drinks_out,//drinks_out=1,output 5$ drinks,drinks_out=2,output 10$ drinks
output reg change_out
);
//首先要知道哪些情况要使用状态机
//购买B饮料(10块),先投5块之后,后面接着投5块,还是投10块
reg [1:0] state;
always@(posedge clk or negedge rst_n)
if(!rst_n)
begin drinks_out <= 2'd0; change_out <= 1'd0; state <= 2'd0;end
else case(sel)
1'd0://购买A饮料,情况很简单
case(din)
2'd0:
begin drinks_out <= 2'd0; change_out <= 1'd0; end
2'd1:
begin drinks_out <= 2'd1; change_out <= 1'd0; end
2'd2:
begin drinks_out <= 2'd1; change_out <= 1'd1; end
default:begin drinks_out <= 2'd0; change_out <= 1'd0; end
endcase
1'd1:
case(din)
2'd0:
begin drinks_out <= 2'd0; change_out <= 1'd0; end
2'd1:
begin
if(state==2'd0)
//买B饮料,第一次投5块,state==1记录一下
begin drinks_out <= 2'd0; change_out <= 1'd0;state <= 2'd1;end
else if(state==2'd1)
//买B饮料,第二次投5块,state==0,返回初始状态
begin drinks_out <= 2'd2; change_out <= 1'd0;state <= 2'd0; end
end
2'd2:
begin
if(state==2'd0)
//买B饮料,第一次投10块。输出后state==0,返回初始状态
begin drinks_out <= 2'd2; change_out <= 1'd0;state <= 2'd0; end
else if(state==2'd1)
//买B饮料,第一次投过5块后,再投10块。输出后state==0,返回初始状态
begin drinks_out <= 2'd2; change_out <= 1'd1;state <= 2'd0;end
end
default:begin drinks_out <= 2'd0; change_out <= 1'd0; end
endcase
default:begin drinks_out <= 2'd0; change_out <= 1'd0; end
endcase
endmodule
