题解 | #自动贩售机1#
自动贩售机1
https://www.nowcoder.com/practice/dcf59e6c51f6489093495acb1bc34dd8
`timescale 1ns/1ns
module seller1(
input wire clk ,
input wire rst ,
input wire d1 ,
input wire d2 ,
input wire d3 ,
output reg out1,
output reg [1:0]out2
);
//*************状态机***********//
parameter idle = 7'b000_0001,
half = 7'b000_0010,
one = 7'b000_0100,
one_half = 7'b000_1000,
two = 7'b001_0000,
two_half = 7'b010_0000,
three = 7'b100_0000;
wire [2:0] pi_money={d3,d2,d1};
reg [6:0] cur_state, next_state;
//第一段:时序逻辑--状态跳转
always@(posedge clk or negedge rst)begin
if(!rst)
cur_state <= idle;
else
cur_state <= next_state ;
end
//第二段:组合逻辑---状态转移(与输入的关系)
always@(*)begin
case(cur_state)
idle:
case(pi_money)
3'b001: next_state = half ;
3'b010: next_state = one ;
3'b100: next_state = two ;
default:next_state = next_state ;
endcase
half:
case(pi_money)
3'b001: next_state = one ;
3'b010: next_state = one_half ;
3'b100: next_state = two_half ;
default: next_state = next_state ;
endcase
one :
case(pi_money)
3'b001: next_state = one_half ;
3'b010: next_state = two ;
3'b100: next_state = three ;
default: next_state = next_state ;
endcase
one_half:next_state = idle ;
two: next_state = idle ;
two_half:next_state = idle ;
three: next_state = idle ;
default: next_state = idle ;
endcase
end
// 第三段:时序逻辑--输出(out1)
always@(posedge clk or negedge rst)begin
if(!rst)
out1 <= 1'b0;
else if ((next_state==one_half)||(next_state==two)||(next_state==two_half)||(next_state==three))
out1 <= 1'b1 ;
else
out1 <= 1'b0;
end
//第三段:时序逻辑--输出(out2)
always@(posedge clk or negedge rst)begin
if(!rst)
out2 <= 2'd0;
else if(next_state==two)
out2 <= 2'd1 ;
else if(next_state==two_half)
out2 <= 2'd2;
else if(next_state==three)
out2 <= 2'd3;
else
out2 <= 2'd0;
end
endmodule


查看20道真题和解析