# Building Larger Circuits ( from HDLBits )

## 1. Counter with period 1000

Build a counter that counts from 0 to 999, inclusive, with a period of 1000 cycles. The reset input is synchronous, and should reset the counter to 0.

### Solution 1

module top_module (
input clk,
input reset,
output [9:0] q);

always@(posedge clk) begin
if (reset)
q <= 10'd0;
else if (q == 999)
q <= 10'd0;
else
q <= q + 10'd1;
end
endmodule

## 2. 4-bit shift register and down counter – (1/5)

This is the first component in a series of five exercises that builds a complex counter out of several smaller circuits. See the final exercise for the overall design.

Build a four-bit shift register that also acts as a down counter. Data is shifted in most-significant-bit first when shift_ena is 1. The number currently in the shift register is decremented when count_ena is 1. Since the full system doesn’t ever use shift_ena and count_ena together, it does not matter what your circuit does if both control inputs are 1 (This mainly means that it doesn’t matter which case gets higher priority).

### solution2

module top_module (
input clk,
input shift_ena,
input count_ena,
input data,
output [3:0] q);

always@(posedge clk) begin
case({shift_ena,count_ena})
2'b10:begin
q <= {q[2:0],data};
end
2'b01:begin
q <= q - 1'b1;
end
default: q <= q;
endcase
end

endmodule


## 3. FSM: Sequence 1101 recognizer – (2/5)

This is the second component in a series of five exercises that builds a complex counter out of several smaller circuits. See the final exercise for the overall design.

Build a finite-state machine that searches for the sequence 1101 in an input bit stream. When the sequence is found, it should set start_shifting to 1, forever, until reset. Getting stuck in the final state is intended to model going to other states in a bigger FSM that is not yet implemented. We will be extending this FSM in the next few exercises.

### solution 3

module top_module (
input clk,
input reset,      // Synchronous reset
input data,
output start_shifting);

parameter S0=3'b000,S1=3'b001,S11=3'b010,S110=3'b011,S1101=3'b100;
reg [2:0] state, next;

always @(posedge clk) begin
if(reset)
state <= S0;
else
state <= next;
end

always @(*) begin
case(state)
S0 		: next = data	?	S1	 :	S0;
S1 		: next = data	?	S11	 :	S0;
S11 	: next = ~data	?	S110 :	S11;
S110 	: next = data 	?	S1101:	S0;
S1101	: next = S1101;
default	: next = state;
endcase
end

assign start_shifting = (state == S1101);
endmodule


## 4. FSM: Enable shift register – (3/5)

This is the third component in a series of five exercises that builds a complex counter out of several smaller circuits. See the final exercise for the overall design.

As part of the FSM for controlling the shift register, we want the ability to enable the shift register for exactly 4 clock cycles whenever the proper bit pattern is detected. We handle sequence detection in Exams/review2015_fsmseq, so this portion of the FSM only handles enabling the shift register for 4 cycles.

Whenever the FSM is reset, assert shift_ena for 4 cycles, then 0 forever (until reset).

### solution 4

module top_module (
input clk,
input reset,      // Synchronous reset
output shift_ena);

reg [2:0] count;

always @(posedge clk) begin
if (reset)
count <= 3'b000;
else if (count == 3'b100)
count <= count;
else
count <= count + 1'b1;
end

assign shift_ena = (~reset) & (~count[2]) | reset;

endmodule


## 5. FSM: the complete FSM – (4/5)

This is the fourth component in a series of five exercises that builds a complex counter out of several smaller circuits. See the final exercise for the overall design.

You may wish to do FSM: Enable shift register and FSM: Sequence recognizer first.

We want to create a timer that:

1. is started when a particular pattern (1101) is detected,
2. shifts in 4 more bits to determine the duration to delay,
3. waits for the counters to finish counting, and
4. notifies the user and waits for the user to acknowledge the timer.

In this problem, implement just the finite-state machine that controls the timer. The data path (counters and some comparators) are not included here.

The serial data is available on the data input pin. When the pattern 1101 is received, the state machine must then assert output shift_ena for exactly 4 clock cycles.

After that, the state machine asserts its counting output to indicate it is waiting for the counters, and waits until input done_counting is high.

At that point, the state machine must assert done to notify the user the timer has timed out, and waits until input ack is 1 before being reset to look for the next occurrence of the start sequence (1101).

The state machine should reset into a state where it begins searching for the input sequence 1101.

Here is an example of the expected inputs and outputs. The ‘x’ states may be slightly confusing to read. They indicate that the FSM should not care about that particular input signal in that cycle. For example, once a 1101 pattern is detected, the FSM no longer looks at the data input until it resumes searching after everything else is done.

### solution 5

1. 首先检测序列（1101）；
2. 检测成功后，依旧通过该串行输入，读取4位作为计数延迟；
3. 等待计数完成（done_counting）；
4. 通知用户该过程已完成（done），并等待用户确认（ack）。

module top_module (
input clk,
input reset,      // Synchronous reset
input data,
output shift_ena,
output counting,
input done_counting,
output done,
input ack );

// declaration
parameter S=0, S1=1, S11=2, S110=3, B0=4, B1=5, B2=6, B3=7, Count=8, Wait=9;
reg [3:0] state,next;

// state transition
always @(*) begin
case (state)
S	:	next = data	?	S1	:	S;
S1	:	next = data	?	S11	:	S;
S11	:	next = data	?	S11	:	S110;
S110:	next = data	?	B0	:	S;
B0	:	next = B1;
B1	:	next = B2;
B2	:	next = B3;
B3	:	next = Count;
Count:	next = done_counting ? Wait : Count;
Wait:	next = ack	?	S	:	Wait;
endcase
end

// state flip-flop
always  @(posedge clk) begin
if(reset)
state <= S;
else
state <= next;
end

// output logic
assign shift_ena = (state == B0)|(state == B1)|(state == B2)|(state == B3);
assign counting = (state == Count);
assign done = (state == Wait);

endmodule


## 6 The complete timer – (5/5) !

This is the fifth component in a series of five exercises that builds a complex counter out of several smaller circuits. You may wish to do the four previous exercises first (countersequence recognizer FSMFSM delay, and combined FSM).

We want to create a timer with one input that:

1. is started when a particular input pattern (1101) is detected,
2. shifts in 4 more bits to determine the duration to delay,
3. waits for the counters to finish counting, and
4. notifies the user and waits for the user to acknowledge the timer.

The serial data is available on the data input pin. When the pattern 1101 is received, the circuit must then shift in the next 4 bits, most-significant-bit first. These 4 bits determine the duration of the timer delay. I’ll refer to this as the delay[3:0].

After that, the state machine asserts its counting output to indicate it is counting. The state machine must count for exactly (delay[3:0] + 1) * 1000 clock cycles. e.g., delay=0 means count 1000 cycles, and delay=5 means count 6000 cycles. Also output the current remaining time. This should be equal to delay for 1000 cycles, then delay-1 for 1000 cycles, and so on until it is 0 for 1000 cycles. When the circuit isn’t counting, the count[3:0] output is don’t-care (whatever value is convenient for you to implement).

At that point, the circuit must assert done to notify the user the timer has timed out, and waits until input ack is 1 before being reset to look for the next occurrence of the start sequence (1101).

The circuit should reset into a state where it begins searching for the input sequence 1101.

Here is an example of the expected inputs and outputs. The ‘x’ states may be slightly confusing to read. They indicate that the FSM should not care about that particular input signal in that cycle. For example, once the 1101 and delay[3:0] have been read, the circuit no longer looks at the data input until it resumes searching after everything else is done. In this example, the circuit counts for 2000 clock cycles because the delay[3:0] value was 4’b0001. The last few cycles starts another count with delay[3:0] = 4’b1110, which will count for 15000 cycles.

### solution 6

1. 增加 [9:0] q 变量用作counter1k的计数；
2. 当计数器count=0并且q=999时，表示完成了计数延时；
3. 当处于Count态，每当q=999时，使向下计数器使能一次；
4. 当不处于Count态时，counter1k始终复位，保持归零；进入Count态时，取消counter1k复位信号。
module top_module (
input clk,
input reset,      // Synchronous reset
input data,
output [3:0] count,	// delay [3:0]
output counting,
output done,
input ack );

// declaration
parameter S=0, S1=1, S11=2, S110=3, B0=4, B1=5, B2=6, B3=7, Count=8, Wait=9;
reg [3:0] state,next;
reg [9:0] q;	// for 1000 counts
wire done_counting;
wire shift_ena;
wire count_ena;

// state transition
always @(*) begin
case (state)
S	:	next = data	?	S1	:	S;
S1	:	next = data	?	S11	:	S;
S11	:	next = data	?	S11	:	S110;
S110:	next = data	?	B0	:	S;
B0	:	next = B1;
B1	:	next = B2;
B2	:	next = B3;
B3	:	next = Count;
Count:	next = done_counting ? Wait : Count;
Wait:	next = ack	?	S	:	Wait;
endcase
end

// instance
shift_and_count U1 (clk, shift_ena, count_ena, data, count);
count1k U2 (clk, ~counting, q);
// state flip-flop
always  @(posedge clk) begin
if(reset)
state <= S;
else
state <= next;
end

// output logic
assign shift_ena = (state == B0)|(state == B1)|(state == B2)|(state == B3);
assign counting = (state == Count);
assign done = (state == Wait);

assign count_ena = counting & (q == 999);
assign done_counting = (count == 0) & (q == 999);

endmodule

// module for shift and count
// Exams/review2015 shiftcount
module shift_and_count (
input clk,
input shift_ena,
input count_ena,
input data,
output [3:0] q);

always@(posedge clk) begin
case({shift_ena,count_ena})
2'b10:begin
q <= {q[2:0],data};
end
2'b01:begin
q <= q - 1'b1;
end
default: q <= q;
endcase
end

endmodule

// module for counting 1000
// Exams/review2015 count1k
module count1k (
input clk,
input reset,
output [9:0] q);

always@(posedge clk) begin
if (reset)
q <= 10'd0;
else if (q == 999)
q <= 10'd0;
else
q <= q + 10'd1;
end
endmodule

## 7. FSM: One-hot logic equations

Given the following state machine with 3 inputs, 3 outputs, and 10 states:

Derive next-state logic equations and output logic equations by inspection assuming the following one-hot encoding is used: (S, S1, S11, S110, B0, B1, B2, B3, Count, Wait) = (10’b0000000001, 10’b0000000010, 10’b0000000100, … , 10’b1000000000)

Derive state transition and output logic equations by inspection assuming a one-hot encoding. Implement only the state transition logic and output logic (the combinational logic portion) for this state machine. (The testbench will test with non-one hot inputs to make sure you’re not trying to do something more complicated).

Write code that generates the following equations:

• B3_next — next-state logic for state B1
• S_next
• S1_next
• Count_next
• Wait_next
• done — output logic
• counting
• shift_ena

### solution 7

module top_module(
input d,
input done_counting,
input ack,
input [9:0] state,    // 10-bit one-hot current state
output B3_next,
output S_next,
output S1_next,
output Count_next,
output Wait_next,
output done,
output counting,
output shift_ena
); //

// You may use these parameters to access state bits using e.g., state[B2] instead of state[6].
parameter S=0, S1=1, S11=2, S110=3, B0=4, B1=5, B2=6, B3=7, Count=8, Wait=9;

// assign B3_next = ...;
// assign S_next = ...;
// etc.
assign B3_next = state[B2];
assign S_next = (~d)&(state[S]|state[S1]|state[S110]) | ack&state[Wait];
assign S1_next = d & state[S];
assign Count_next = state[B3] | (state[Count] & ~done_counting);
assign Wait_next = (state[Count] & done_counting) | (state[Wait]& ~ack);
assign done = state[Wait];
assign counting = state[Count];
assign shift_ena = state[B0]|state[B1]|state[B2]|state[B3];

endmodule