题解 | #自动售卖机#
自动售卖机
https://www.nowcoder.com/practice/487953e6d3e3434988e0dd6960b6c9f8
题解都是米利型,确实更为简单,但为了学习的完整性,在这放一个摩尔型的解题思路。
`timescale 1ns/1ns
module sale(
input clk ,
input rst_n ,
input sel ,
input [1:0] din ,
output reg [1:0] drinks_out,
output reg change_out
);
parameter IDLE = 4'd0001;
parameter S_5 = 4'd0010;
parameter S_10 = 4'd0100;
parameter S_15 = 4'd1000;
reg [3:0] curr_state, next_state;
always @(posedge clk, negedge rst_n) begin
if (~rst_n) begin
curr_state <= IDLE;
next_state <= IDLE;
end
else begin
curr_state <= next_state;
end
end
wire [2:0] data_in;
assign data_in = {sel, din};
always @(*) begin
case (curr_state)
IDLE: begin
casex (data_in)
3'bx00: next_state = IDLE;
3'bx01: next_state = S_5;
3'bx10: next_state = S_10;
default: next_state = IDLE;
endcase
end
S_5: begin
casex (data_in)
3'b000: next_state = IDLE;
3'b001: next_state = S_5;
3'b010: next_state = S_10;
3'b100: next_state = S_5;
3'b101: next_state = S_10;
3'b110: next_state = S_15;
default: next_state = IDLE;
endcase
end
S_10: begin
casex (data_in)
3'bx00: next_state = IDLE;
3'bx01: next_state = S_5;
3'bx10: next_state = S_10;
default: next_state = IDLE;
endcase
end
S_15: begin
casex (data_in)
3'b100: next_state = IDLE;
3'b101: next_state = S_5;
3'b110: next_state = S_10;
default: next_state = IDLE;
endcase
end
endcase
end
always @(posedge clk, negedge rst_n) begin
case (next_state)
S_5: begin
drinks_out <= (sel) ? 'd0 : 'd1;
change_out <= 'd0;
end
S_10: begin
drinks_out <= (sel) ? 'd2 : 'd1;
change_out <= (sel) ? 'd0 : 'd1;
end
S_15: begin
drinks_out <= 'd2;
change_out <= 'd1;
end
default: begin
drinks_out <= 'd0;
change_out <= 'd0;
end
endcase
end
endmodule
查看23道真题和解析