|
发表于 2016-8-10 16:32:19
|
显示全部楼层
// Description: 简单的自动售饮料机,假定一瓶饮料价格为2元5角,投币分别为一元和五角两种硬币。
// 每次投入硬币为一元或者五角,如果投入金币的总和是两元五角时,输出一瓶饮料;
// 如果投币总和是三元时,输出一瓶饮料,并且找回五角。
//
// 三段式方法
// 消除state latch
module drink_machine(rst,clk,onedollar_in,fifty_in,fifty_out,drink_out);
parameter IDLE = 0;
parameter ZERO_FIFTY = 1;
parameter ONE = 2;
parameter ONE_FIFTY = 3;
parameter TWO = 4;
input clk;
input fifty_in;
input onedollar_in;
input rst;
output fifty_out;
output drink_out;
reg fifty_out,drink_out;
reg[2:0] state,next_state;
//state switch each cycle
always@(posedge clk or negedge rst)
begin
if(!rst)
state <= IDLE;
else
state <= next_state;
end
//next_state judge
always@(onedollar_in or fifty_in or rst)
begin
if(!rst)
begin
next_state = IDLE;
end
else
begin
case(state)
IDLE:
begin
if(fifty_in)
next_state = ZERO_FIFTY;
else if(onedollar_in)
next_state = ONE;
else
next_state = IDLE;
end
ZERO_FIFTY:
begin
if(fifty_in)
next_state = ONE;
else if(onedollar_in)
next_state = ONE_FIFTY;
else
next_state = ZERO_FIFTY;
end
ONE:
begin
if(fifty_in)
next_state = ONE_FIFTY;
else if(onedollar_in)
next_state = TWO;
else
next_state = ONE;
end
ONE_FIFTY:
begin
if(fifty_in)
next_state = TWO;
else if(onedollar_in)
next_state = IDLE;
else
next_state = ONE_FIFTY;
end
TWO:
begin
if(fifty_in || onedollar_in)
next_state = IDLE;
else
next_state = TWO;
end
default: next_state = IDLE;
endcase
end
//reg output to remove glitch
always@(posedge clk or negedge rst)
begin
if(!rst)
begin
drink_out <= 0;
end
else if (next_state==TWO)
begin
drink_out <= 1;
end
end
always@(posedge clk or negedge rst)
begin
if(!rst)
begin
fifty_out <= 0;
end
else if ((next_state==TWO)&&(onedollar_in))
begin
fifty_out <= 1;
end
end
endmodule |
|