---
title: '`for` loops in Verilog'
...

# For Loops in Verilog

A `for` loop in Verilog is similar to the `for` loop in C. Most often a Verilog
loop is used for **combinational logic**, comprised of **blocking assignments**
(`=` as opposed to `<=`). A simple example is given in `src/add_bits.v`, which
computes the sum over all bits in a vector:

```
   always @(a) begin
      q = 0;

      for (idx=0; idx<8; idx=idx+1) begin
          q = q + a[idx];
      end
   end
```

The lines in this block are evaluated sequentially, one after the other. Imagine
the successive evaluations laid out like dominos. Although they are evaluated
in sequence, the whole sequence must complete -- every domino must fall -- before
the next clock cycle arrives. After synthesis, the circuit looks like a lineup of
combinational adders: 

```text
 0 -->[+]-->[+]-->[+]-->[+]-->[+]-->[+]-->[+]-->[+]--> q 
       ^     ^     ^     ^     ^     ^     ^     ^   
       |     |     |     |     |     |     |     |    
      a[0]  a[1]  a[2]  a[3]  a[4]  a[5]  a[6]  a[7]  
```


# Assigned Tasks

Create a `top` module to contain `add_bits` as a submodule instance. In the
`top` module, do the following:

* Declare top level inputs `clk`, `load`, (1 bit), and `a` (8-bits)
* Declare top level output `q` (4 bits)
* Declare an internal 8-bit `reg` named `_a` (the underscore (`_`) distinguishes it as a separate wire from the port `a`)
* Declare an internal 4-bit `wire` named `_q`
* Instantate the `add_bits` module, and name the instance `add_bits_instance`
* Connect submodule ports:
    - `_a` to `add_bits_instance.a` 
    - `_q` to `add_bits_instance.q`
* Make a **posedge clocked** `always` block with this behavior: 
    - Always assign `q <= _q`
    - `if` `load` is 1, then assign `_a <= a`

A `testbench` template is provided in `src/testbench.v`. Modify the `testbench` to
test your `top` module. Specifically, you need to declare a `wire` for `q`, instantiate
`top`, connect its ports, and make additional `$write` and `$fwrite` statements to report
`q` in the log text. Simulate your design to verify that `q` is correct for several
random values of `a`.

When verified, create an XDC file (use `Basys3_Master.xdc` as a template) and map
`a` to the lower (right-most) switches, `load` to `btnU`, and `q` to the lower 4
`led` signals. Edit `build.tcl` as needed, then **implement the design**.

Open the timing report and note the WNS.

Program your design onto the Basys3 board and test the following cases:

1. `a = 8'b0000_0001`
2. `a = 8'b0101_0101`
3. `a = 8'b1111_1111`

Save a photo of your board for each test case, with filenames `case1`, `case2`, and
`case3`. Save the photo files with the appropriate graphics file suffix (`.png`, `.jpg`, etc).

Turn in your work using `git`:

```bash
git add case* src/*.v *.rpt *.txt *.tcl *.bit *.xdc
git commit . -m "Complete"
git push origin main
```

Indicate on Canvas that your assignment is done.
