题解 | #自动贩售机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
);
/*
//这是一个不完全正确的mealy状态机,输出取决于当前输入和状态。单状态图值得学习
localparam s0=0,s05=1,s1=2,s15=3,s2=4,s25=5,s3=6;
reg [2:0] state,next_state;
always@(posedge clk or negedge rst)
if(~rst)
state<=0;
else
state<=next_state;
always@(*)begin
next_state=s0;
case(state)
s0:next_state=d1?s05:
d2?s1:
d3?s2:s0;
s05:next_state=d1?s1:
d2?s15:
d3?s25:s05;
s1:next_state=d1?s15:
d2?s2:
d3?s3:s1;
s15, s2, s25, s3: next_state = s0;
endcase
end
always@(*)
if(~rst)
out1=0;
else
out1=state==s15||state==s2||state==s25||state==s3;
//这个输出方法也值得学习,少写了很多状态
always@(*) begin
if(~rst)
out2 <= 0;
else
case(state)
s2 : out2 <= 1;
s25 : out2 <= 2;
s3 : out2 <= 3;
default : out2 <= 0;
endcase
end
*/
parameter S0=0, S0_5=1, S1=2, S1_5=3, S2=4, S2_5=5, S3=6;
reg [2:0] state, nstate;
always@(negedge clk or negedge rst) begin
if(~rst)
state <= S0;
else
state <= nstate;
end
always@(*) begin
case(state)
S0 : nstate = d1? S0_5:
d2? S1 :
d3? S2 :
nstate;
S0_5 : nstate = d1? S1 :
d2? S1_5:
d3? S2_5:
nstate;
S1 : nstate = d1? S1_5:
d2? S2 :
d3? S3 :
nstate;
S1_5, S2, S2_5, S3: nstate = S0;
default : nstate = S0;
endcase
end
always@(posedge clk or negedge rst) begin
if(~rst)
out1 <= 0;
else
out1 <= state==S1_5||state==S2||state==S2_5||state==S3;
end
always@(posedge clk or negedge rst) begin
if(~rst)
out2 <= 0;
else
case(state)
S0, S0_5, S1, S1_5: out2 <= 0;
S2 : out2 <= 1;
S2_5 : out2 <= 2;
S3 : out2 <= 3;
default : out2 <= 0;
endcase
end
//*************code***********//
endmodule
关键是要有negedge来更新周期。

