题解 | #自动售卖机#
自动售卖机
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
);
localparam S0 = 1'd0;
localparam S5 = 1'd1;
reg state, state_nxt;
always @(posedge clk or negedge rst_n) begin
if (!rst_n) begin
state <= S0;
end else begin
state <= state_nxt;
end
end
always @(*) begin
case(state)
S0 : state_nxt = (din == 2'd1 && sel) ? S5 : state;
S5 : state_nxt = (din != 2'd0) ? S0 : state;
default : state_nxt = S0;
endcase
end
always @(posedge clk or negedge rst_n) begin
if (!rst_n) begin
drinks_out <= 2'd0;
change_out <= 1'b0;
end else begin
case(state)
S0 : begin
drinks_out <= (din != 2'd0 && !sel) ? 2'd1 :
(din == 2'd2 && sel) ? 2'd2 :
2'd0;
change_out <= (din == 2'd2 && !sel);
end
S5 : begin
drinks_out <= (din != 2'd0) ? 2'd2 : 2'd0;
change_out <= din == 2'd2;
end
endcase
end
end
endmodule

