Getting started

This section demonstrates the basic nMigen workflow to provide a cursory overview of the language and the toolchain. See the tutorial for a step-by-step introduction to the language, and the language guide for a detailed explanation of every language construct.

A counter

As a first example, consider a counter with a fixed limit, enable, and overflow. The code for this example is shown below. Download and run it:

$ python3 up_counter.py

Implementing a counter

A 16-bit up counter with enable input, overflow output, and a limit fixed at design time can be implemented in nMigen as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
from nmigen import *


class UpCounter(Elaboratable):
    """
    A 16-bit up counter with a fixed limit.

    Parameters
    ----------
    limit : int
        The value at which the counter overflows.

    Attributes
    ----------
    en : Signal, in
        The counter is incremented if ``en`` is asserted, and retains
        its value otherwise.
    ovf : Signal, out
        ``ovf`` is asserted when the counter reaches its limit.
    """
    def __init__(self, limit):
        self.limit = limit

        # Ports
        self.en  = Signal()
        self.ovf = Signal()

        # State
        self.count = Signal(16)

    def elaborate(self, platform):
        m = Module()

        m.d.comb += self.ovf.eq(self.count == self.limit)

        with m.If(self.en):
            with m.If(self.ovf):
                m.d.sync += self.count.eq(0)
            with m.Else():
                m.d.sync += self.count.eq(self.count + 1)

        return m

The reusable building block of nMigen designs is an Elaboratable: a Python class that includes HDL signals (en and ovf, in this case) as a part of its interface, and provides the elaborate method that defines its behavior.

Most elaborate implementations use a Module helper to describe combinatorial (m.d.comb) and synchronous (m.d.sync) logic controlled with conditional syntax (m.If, m.Elif, m.Else) similar to Python’s. They can also instantiate vendor-defined black boxes or modules written in other HDLs.

Testing a counter

To verify its functionality, the counter can be simulated for a small amount of time, with a test bench driving it and checking a few simple conditions:

44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
from nmigen.sim import Simulator


dut = UpCounter(25)
def bench():
    # Disabled counter should not overflow.
    yield dut.en.eq(0)
    for _ in range(30):
        yield
        assert not (yield dut.ovf)

    # Once enabled, the counter should overflow in 25 cycles.
    yield dut.en.eq(1)
    for _ in range(25):
        yield
        assert not (yield dut.ovf)
    yield
    assert (yield dut.ovf)

    # The overflow should clear in one cycle.
    yield
    assert not (yield dut.ovf)


sim = Simulator(dut)
sim.add_clock(1e-6) # 1 MHz
sim.add_sync_process(bench)
with sim.write_vcd("up_counter.vcd"):
    sim.run()

The test bench is implemented as a Python generator function that is co-simulated with the counter itself. The test bench can inspect the simulated signals with yield sig, update them with yield sig.eq(val), and advance the simulation by one clock cycle with yield.

When run, the test bench finishes successfully, since all of the assertions hold, and produces a VCD file with waveforms recorded for every Signal as well as the clock of the sync domain:

A screenshot of GTKWave displaying waveforms near the clock cycle where the counter overflows.

Converting a counter

Although some nMigen workflows do not include Verilog at all, it is still the de facto standard for HDL interoperability. Any nMigen design can be converted to synthesizable Verilog using the corresponding backend:

74
75
76
77
78
79
from nmigen.back import verilog


top = UpCounter(25)
with open("up_counter.v", "w") as f:
    f.write(verilog.convert(top, ports=[top.en, top.ovf]))

The signals that will be connected to the ports of the top-level Verilog module should be specified explicitly. The rising edge clock and synchronous reset signals of the sync domain are added automatically; if necessary, the control signals can be configured explicitly. The result is the following Verilog code (lightly edited for clarity):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
(* generator = "nMigen" *)
module top(clk, rst, en, ovf);
  (* src = "<nmigen-root>/nmigen/hdl/ir.py:526" *)
  input clk;
  (* src = "<nmigen-root>/nmigen/hdl/ir.py:526" *)
  input rst;
  (* src = "up_counter.py:26" *)
  input en;
  (* src = "up_counter.py:27" *)
  output ovf;
  (* src = "up_counter.py:30" *)
  reg [15:0] count = 16'h0000;
  (* src = "up_counter.py:30" *)
  reg [15:0] \count$next ;
  (* src = "up_counter.py:35" *)
  wire \$1 ;
  (* src = "up_counter.py:41" *)
  wire [16:0] \$3 ;
  (* src = "up_counter.py:41" *)
  wire [16:0] \$4 ;
  assign \$1  = count == (* src = "up_counter.py:35" *) 5'h19;
  assign \$4  = count + (* src = "up_counter.py:41" *) 1'h1;
  always @(posedge clk)
      count <= \count$next ;
  always @* begin
    \count$next  = count;
    (* src = "up_counter.py:37" *)
    casez (en)
      /* src = "up_counter.py:37" */
      1'h1:
          (* src = "up_counter.py:38" *)
          casez (ovf)
            /* src = "up_counter.py:38" */
            1'h1:
                \count$next  = 16'h0000;
            /* src = "up_counter.py:40" */
            default:
                \count$next  = \$3 [15:0];
          endcase
    endcase
    (* src = "<nmigen-root>/nmigen/hdl/xfrm.py:518" *)
    casez (rst)
      1'h1:
          \count$next  = 16'h0000;
    endcase
  end
  assign \$3  = \$4 ;
  assign ovf = \$1 ;
endmodule

To aid debugging, the generated Verilog code has the same general structure as the nMigen source code (although more verbose), and contains extensive source location information.

Note

Unfortunately, at the moment none of the supported toolchains will use the source location information in diagnostic messages.

A blinking LED

Although nMigen works well as a standalone HDL, it also includes a build system that integrates with FPGA toolchains, and many board definition files for common developer boards that include pinouts and programming adapter invocations. The following code will blink a LED with a frequency of 1 Hz on any board that has a LED and an oscillator:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
from nmigen import *


class LEDBlinker(Elaboratable):
    def elaborate(self, platform):
        m = Module()

        led = platform.request("led")

        half_freq = int(platform.default_clk_frequency // 2)
        timer = Signal(range(half_freq + 1))

        with m.If(timer == half_freq):
            m.d.sync += led.eq(~led)
            m.d.sync += timer.eq(0)
        with m.Else():
            m.d.sync += timer.eq(timer + 1)

        return m

The LEDBlinker module will use the first LED available on the board, and derive the clock divisor from the oscillator frequency specified in the clock constraint. It can be used, for example, with the Lattice iCEStick evaluation board, one of the many boards already supported by nMigen:

Todo

Link to the installation instructions for the FOSS iCE40 toolchain, probably as a part of board documentation.

21
22
23
24
from nmigen_boards.icestick import *


ICEStickPlatform().build(LEDBlinker(), do_program=True)

With only a single line of code, the design is synthesized, placed, routed, and programmed to the on-board Flash memory. Although not all applications will use the nMigen build system, the designs that choose it can benefit from the “turnkey” built-in workflows; if necessary, the built-in workflows can be customized to include user-specified options, commands, and files.

Note

The ability to check with minimal effort whether the entire toolchain functions correctly is so important that it is built into every board definition file. To use it with the iCEStick board, run:

$ python3 -m nmigen_boards.icestick

This command will build and program a test bitstream similar to the example above.