题意整理
money是预付费,根据boost的值递减,boost为0时,每个时钟减一,boost为1时,每个时钟减2。同时把每个时刻变化之后的值作为remain的值输出。当set为1时,表示玩家续费,将money的值加到remain上。当remain小于10时,将yellow的值置为1。当费用不足时,将red的值置为1,yellow的值置为0。
值得注意的是:由于在boost情况下,每个时钟remain的数值减二,所以remain不一定可以达到0,费用不足应包括两个情况:remain=0或remain =1 &&boost=1。题解主体
首先明确remain的取值,当费用不足时(remain == 0 || (remain==1&&boost)),remain的值保持为0。在boost的值为0时,remain每个时钟减一;boost为1时,remain的值每个时钟减二。当set信号有效,应把money的数值加到remain之中。always @(posedge clk or negedge rst_n)
begin
if(!rst_n)
remain <= 0;
else if (set)
remain <= money + remain;
else if (remain == 0 || (remain==1&&boost))
remain <= remain;
else
begin
if (!boost)
remain <= remain -1;
else if (boost)
remain <= remain -2;
else remain <= remain;
end
end 然后明确指示灯的逻辑:当remain小于10时,将yellow的值置为1。remain=0或remain =1 &&boost=1时,将red的值置为1,yellow的值置为0。
always @(posedge clk or negedge rst_n)
if(!rst_n)
begin
yellow <= 1'd0;
red <= 1'd0;
end
else if (remain <10 && remain !== 0)
begin
yellow <= 1'd1;
red <= 1'd0;
end
else if (remain == 0 || (remain==1&&boost))
begin
yellow <= 1'd0;
red <= 1'd1;
end
参考答案
`timescale 1ns/1ns module game_count ( input rst_n, //异位复位信号,低电平有效 input clk, //时钟信号 input [9:0]money, input set, input boost, output reg[9:0]remain, output reg yellow, output reg red ); always @(posedge clk or negedge rst_n) begin if(!rst_n) remain <= 0; else if (set&&!boost) remain <= money + remain -1; else if (set&&!boost) remain <= money + remain -2; else if (remain == 0 || (remain==1&&boost)) remain <= remain; else begin if (!boost) remain <= remain -1; else if (boost) remain <= remain -2; else remain <= remain; end end always @(posedge clk or negedge rst_n) if(!rst_n) begin yellow <= 1'd0; red <= 1'd0; end else if (remain <12 && remain !== 0) begin yellow <= 1'd1; red <= 1'd0; end else if (remain == 0 || (remain==1&&boost)) begin yellow <= 1'd0; red <= 1'd1; end else begin yellow <= 1'd0; red <= 1'd0; end endmodule