题解 | #自动贩售机2#
自动贩售机2
https://www.nowcoder.com/practice/298dec1c3dce45c881f3e53e02558828
状态机,行数虽多,但是简洁明了。
`timescale 1ns/1ns module seller2( input wire clk , input wire rst , input wire d1 , input wire d2 , input wire sel , output reg out1 , //饮料1(1.5元) output reg out2 , //饮料2(2.5元) output reg out3 //找零(0.5元) ); reg [3:0] state, next_state; wire [2:0] d = {sel,d2,d1}; //饮料种类与投币 // 组合逻辑中使用锁存结构检测脉冲 always @(*) begin case(state) 0: begin case (d) 4'b001:next_state = 1; 4'b010:next_state = 2; 4'b101:next_state = 1; 4'b110:next_state = 2; default: next_state = next_state; endcase end //未投币 1: begin case (d) 4'b001:next_state = 2; 4'b010:next_state = 5; //准备找零0,输出饮料1 4'b101:next_state = 2; 4'b110:next_state = 3; default: next_state = next_state; endcase end //投币0.5 2: begin case (d) 4'b001:next_state = 5; //准备找零0,输出饮料1 4'b010:next_state = 6; //准备找零0.5,输出饮料1 4'b101:next_state = 3; 4'b110:next_state = 4; default: next_state = next_state; endcase end //投币1 3: begin case (d) 4'b101:next_state = 4; 4'b110:next_state = 7; //准备找零0,输出饮料2 default: next_state = next_state; endcase end //投币1.5 4: begin case (d) 4'b101:next_state = 7; //准备找零0,输出饮料2 4'b110:next_state = 8; //准备找零0.5,输出饮料2 default: next_state = next_state; endcase end //投币2 default: next_state = 0; endcase end always @(posedge clk,negedge rst) begin if(!rst) begin state <= 0; end else begin state <= next_state; end end //由于组合逻辑使用锁存器结构,所以可以使用posedge触发 always @(*) begin if (!rst) begin out1 = 0; out2 = 0; out3 = 0; end else begin case(state) 5: begin out1 = 1; out2 = 0; out3 = 0; end 6: begin out1 = 1; out2 = 0; out3 = 1; end 7: begin out1 = 0; out2 = 1; out3 = 0; end 8: begin out1 = 0; out2 = 1; out3 = 1; end default: begin out1 = 0; out2 = 0; out3 = 0; end endcase end end endmodule