题解 | #自动售卖机#

自动售卖机

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   
);
//写状态机主要是为了处理:买B饮料但只投了5元的情况
reg [1:0] state ,nxt_state;
parameter idle = 2'b01,
          B_DIN1 = 2'b10;
always@(posedge clk or negedge rst_n) 
  if(!rst_n)
    state <= idle;
  else 
    state <= nxt_state;

always@(*)
  case(state)
    idle:begin
          if(sel==1 && din==1)
            nxt_state <= B_DIN1;
          else
            nxt_state <= idle;
    end
    B_DIN1: begin
             if(din==0) 
                nxt_state <= B_DIN1; //直到这5元钱算清楚再跳出去
             else       
                nxt_state <=idle;
            end
    default: nxt_state <=idle;
  endcase

//drinks_out
always@(posedge clk or negedge rst_n) begin
  if(!rst_n)
      drinks_out <= 0;
  else if(sel==0 && state==idle && din>2'd0)
      drinks_out <= 2'd1;
  else if((sel==1 && state==idle && din==2'd2)||(sel==1 && state==B_DIN1 && din>2'd0))
  //我真是傻了,一直提示这里有编译错误,后来发现是少个括号,写下来提醒自己一下这个愚蠢的小错误
       drinks_out <= 2'd2;
  else 
      drinks_out <= 2'd0;
end  

//change_out
always@(posedge clk or negedge rst_n) begin 
  if(!rst_n)
    change_out <= 0;
  else if((sel==0 && din==2'd2)||(sel==1 && state==B_DIN1 && din==2'd2))
     change_out <= 1;
  else 
     change_out <= 0;
end

endmodule

全部评论

相关推荐

ddd7_:跟我一模一样,加微信的hr都同一个,扫码了白年书人查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务