Verilog Code
module Q41(clk,q1,reset,q2);
input clk,reset;
output [7:0] q1,q2;
reg [7:0] q1,q2;
reg a;
always @(posedge clk or posedge reset)
begin
if(reset)
begin
a <= 0 ;
q1 <= 8'h0;
q2 <= 8'h0;
end
else if(a<=0)
begin
if(q1>=8'h14)
begin q1 <= 8'h14; a <= 1; end
else
q1 <= q1+1;
end
else
begin
if(q1<=8'h0)
begin q1 <= 8'h0; a <= 0; end
else
q1 <= q1-1;
end
if(a<=0)
q2 <=q2+q1;
else
q2 <=q2-q1;
end
endmodule
Test Bench
`timescale 1ps/1ps
module Q41TestBench;
reg clk;
reg reset;
wire [7:0] q1;
wire [7:0] q2;
parameter step = 10000; // 10ns
Q41 uut (clk, q1, reset, q2);
always begin
clk = 0; #(step/2);
clk = 1; #(step/2);
end
initial begin
reset = 1;
#step reset = 0;
#step clk = 0;
#(step*100) $finish;
end
initial $monitor($stime,
" clk = %d reset = %d Q = %d",clk,reset,q2);
endmodule
Result
view result image
Your problem is that you have placed Q2 in two separate constructs. You have Q2 reset in your traditional IF(reset) and then you have a separate IF managing the assignment of Q2. I'll recommend the following recode where q2 is in the same IF construct.
if(reset)
begin
a <= 0 ;
q1 <= 8'h0;
q2 <= 8'h0;
end
else if(a<=0)
begin
q2 <= q2+q1
if(q1>=8'h14)
begin
q1 <= 8'h14;
a <= 1;
end
else
begin
q1 <= q1+1;
a <= a; // I like to make sure that everything is always assigned
end
end
else
begin
q2 <=q2-q1;
if(q1<=8'h0)
begin
q1 <= 8'h0;
a <= 0;
end
else
begin
q1 <= q1-1;
a <= a;
end
end