Skip to content
systemcoding.dev
Hardware

The Complete Guide to Open-Source FPGA Toolchains

How open-source FPGA toolchains work: Yosys, nextpnr, IceStorm, Trellis and loaders, with a full iCE40 and ECP5 build, constraints, timing and CI.

25 min read
Summarize in AI
Flat illustration of logic gates wired into a small circuit, with the GNU, SparkFun and KiCad logos.

For most of FPGA history, building a design meant installing a vendor suite that weighed tens of gigabytes, ran on a limited set of operating systems and kept its bitstream format secret. Over the past decade that changed for several device families. Reverse-engineered bitstream documentation, a synthesis framework called Yosys and a place-and-route tool called nextpnr now make it possible to go from Verilog to a programmed board with a handful of small command-line programs that install in minutes and run in seconds. This guide explains how those tools fit together, what each stage does, how to drive them for a Lattice iCE40 and an ECP5 board, how to read their reports, where they stop and vendor tools take over, and how to script the whole flow for continuous integration. It assumes you can read basic Verilog, as covered in the first guide of this cluster, and defines the FPGA terms as they appear. Command-line examples describe Yosys 0.40, nextpnr 0.7, Project IceStorm, Project Trellis and openFPGALoader 0.12.

What an FPGA toolchain has to do

A field-programmable gate array is a chip full of small configurable blocks joined by configurable wiring. Its configuration lives in memory cells that are loaded at power-up, either from a flash chip on the board or from a programmer. The file that holds those cells' values is the bitstream. Turning a design into a bitstream takes five steps, and every toolchain, open or commercial, follows them.

  1. Synthesis reads your hardware description and produces a netlist: a graph of generic logic gates, flip-flops and memories.

  2. Technology mapping converts that graph into the chip's own building blocks, for example lookup tables, flip-flops, carry cells and block RAMs.

  3. Place decides which physical block on the chip hosts each mapped cell.

  4. Route chooses which wires and switches connect the placed blocks, so that every signal reaches its destinations in time.

  5. Pack writes the resulting configuration, every switch and every table, in the chip's bitstream format.

A sixth step, program, loads the bitstream into the device or its flash. Timing analysis runs alongside placement and routing: after the tool chooses wires, it adds up delays along every path and reports whether the design meets the clock frequency you asked for.

The open toolchains split these steps across separate programs that talk through text and JSON files. That makes each stage easy to inspect, replace and script, and it is the main reason the open flow is pleasant to use.

The pieces

Yosys

Yosys is a framework for Verilog synthesis. It reads Verilog and parts of SystemVerilog, runs a long series of passes that transform the design, and writes the result in several formats. For FPGAs, the relevant commands are the architecture-specific scripts: synth_ice40 for the iCE40 family, synth_ecp5 for the ECP5, synth_gowin for Gowin parts, synth_xilinx for 7-series devices and several others. Each script runs the general passes, maps memories and arithmetic to the chip's primitives, converts logic to lookup tables with the ABC logic optimiser, and writes a JSON netlist.

Yosys is also where you find design statistics, formal verification hooks through SymbiYosys, and a built-in interpreter for scripts. The stat command prints a count of cells, which is the first measurement of how large your design is.

nextpnr

nextpnr is the place-and-route tool. It reads Yosys's JSON netlist, a constraints file, and a description of the target chip, then places and routes the design with a timing-driven algorithm. It comes as separate executables for each architecture: nextpnr-ice40, nextpnr-ecp5, nextpnr-gowin and, built on the common "himbaechel" framework, several more. After routing it prints a timing report, and it writes a textual or binary description of the configuration.

Bitstream packers and the projects behind them

The step that turns nextpnr's output into a bitstream depends on documentation of the chip's configuration format, which vendors usually do not publish. Community projects reverse-engineered them:

  • Project IceStorm documents the iCE40 family. Its tools include icepack, which turns the text ASCII configuration into a binary bitstream, iceprog, which programs a board over an FTDI USB chip, icetime, a timing analyser and icepll, a PLL parameter calculator.

  • Project Trellis documents the ECP5. Its packer is ecppack, which writes a bitstream, and it also supplies the chip database nextpnr uses.

  • Project Apicula does the same for Gowin's small FPGAs, found on cheap boards such as the Tang Nano family.

  • Project X-Ray and related work documents Xilinx 7-series devices, and the F4PGA effort builds a flow on top of it. This flow is more complex and less mature than the Lattice ones.

Loaders

A loader sends a bitstream to the board. iceprog is the iCE40 tool. openFPGALoader is a universal programmer that supports many boards, cables and chip families, including iCE40, ECP5, Gowin and Xilinx parts, over JTAG, SPI and USB interfaces. For a board it knows by name, openFPGALoader -b <board> file is usually all it takes.

Simulators and viewers

Simulation does not need the FPGA tools. Icarus Verilog and Verilator simulate Verilog, GHDL simulates VHDL, and GTKWave displays waveform files. They are separate programs, and the earlier posts in this cluster use them.

Where to get them

The simplest route is a prebuilt bundle. The OSS CAD Suite, published by the Yosys project, packages Yosys, nextpnr for several architectures, the IceStorm and Trellis tools, openFPGALoader, Icarus Verilog, Verilator, GTKWave, SymbiYosys and more in one archive for Linux, macOS and Windows. You unpack it and source an environment script, and every tool is on your path. Distribution packages and Homebrew formulas exist for several of the tools as well, though versions vary.

The flow end to end for iCE40

Take the blinking LED from the first guide in this cluster. The file blink.v has one clock input and one output. A constraints file ties them to pins. The target in this walkthrough is an iCEBreaker board, which carries an iCE40 UP5K in a 48-pin package, a 12 MHz oscillator and a pair of active-low LEDs. Pin numbers and chip variant come from the board's documentation, and you should always confirm them there.

blink.vverilog
module blink (
    input  wire clk,
    output wire led
);
    reg [23:0] counter = 24'd0;

    always @(posedge clk)
        counter <= counter + 24'd1;

    assign led = ~counter[23];
endmodule

The LED on this board lights when the pin is low, so the output is inverted. The constraint file names the pins:

blink.pcfText
set_io clk 35
set_io led 11

Four commands carry the design from source to a programmed board. Each is one stage.

Shell
yosys -q -p "read_verilog blink.v; synth_ice40 -top blink -json blink.json"
nextpnr-ice40 --up5k --package sg48 --json blink.json --pcf blink.pcf --asc blink.asc --freq 12
icepack blink.asc blink.bin
iceprog blink.bin

The first command runs Yosys quietly with an inline script: read the file, synthesise for iCE40 with blink as the top module, and write blink.json. The second runs place and route for the UP5K in the SG48 package, reading the netlist and the pin file, writing a textual configuration blink.asc, and checking timing against a 12 MHz target. The third packs the text configuration into a binary bitstream. The fourth sends it to the board.

nextpnr's console output is informative, and learning to read it pays off. The sections that matter most are the utilisation summary near the end of placement and the timing report after routing. A trimmed example shows their shape:

Text
Info: Device utilisation:
Info:            ICESTORM_LC:    24/ 5280     0%
Info:           ICESTORM_RAM:     0/   30     0%
Info:                  SB_IO:     2/   96     2%
Info:                  SB_GB:     1/    8    12%

Info: Max frequency for clock 'clk_$glb_clk': 215.04 MHz (PASS at 12.00 MHz)

The figures here are illustrative of the format and will differ in your run. The first block says how many of each resource the design uses. The last line says the slowest path would allow the clock to run at the stated frequency, and that the 12 MHz target passes with room to spare.

The same flow for ECP5

The structure is identical. Only the names change. For a ULX3S board, which carries an ECP5 LFE5U-85F, the commands are:

Shell
yosys -q -p "read_verilog blink.v; synth_ecp5 -top blink -json blink.json"
nextpnr-ecp5 --85k --package CABGA381 --json blink.json --lpf blink.lpf --textcfg blink.config --freq 25
ecppack --compress blink.config blink.bit
openFPGALoader -b ulx3s blink.bit

The constraint file uses Lattice's LPF format, which names a site and an I/O standard for each port, and a frequency for the clock:

blink.lpfText
LOCATE COMP "clk" SITE "G2";
IOBUF PORT "clk" IO_TYPE=LVCMOS33;
FREQUENCY PORT "clk" 25 MHZ;
LOCATE COMP "led" SITE "B2";
IOBUF PORT "led" IO_TYPE=LVCMOS33;

The ULX3S oscillator runs at 25 MHz, so the counter bit used for the blink should be one position lower than on a 12 MHz board for a similar rate, because 25 MHz is about twice 12 MHz. The pin names again come from the board's schematic, and the design stays the same apart from the bit index.

Pin constraints and timing constraints

Two kinds of constraint reach the tools, and it helps to keep them separate.

Physical constraints place ports on pins and set electrical standards. For iCE40 they are lines in a PCF file, written set_io port pin. For ECP5 they are LPF statements. These tell the router where a signal enters and leaves the chip, and they must match the board.

Timing constraints state how fast the design must run. The simplest form for a single-clock design is a frequency given on the command line, --freq 12 for nextpnr-ice40. Designs with several clocks or with tight input and output timing need more, and the later posts in this cluster treat them. Without a target, nextpnr uses a default that may be far from what you need, so always state it.

Reading the logs for problems

Most failures show up as one of a few messages, and recognising them speeds up work.

  • A port with no pin. nextpnr warns that a top-level port was not constrained, and may place it arbitrarily. A clock without a pin is the usual cause of a design that builds and does nothing.

  • A pin assigned to a port that does not exist. Check that the names in the constraint file match the module's ports exactly, including capitalisation.

  • Utilisation over 100 percent. The design does not fit. Look at the stat report from Yosys to see which cell type is the culprit, often a memory that was not mapped to block RAM or a multiplier built from lookup tables.

  • Timing failure. The report ends with FAIL at <target> MHz. Read the critical path listing, which names the source, the destination and each stage's delay, and shorten that path, usually by adding a pipeline register.

  • Latch warnings from Yosys. Treat Latch inferred as an error and fix the combinational block, as covered in the earlier post on defaults.

nextpnr uses a random seed for placement, and different seeds give different results. When a design misses timing narrowly, --seed followed by a number runs another placement. That is a legitimate tactic for closing a small gap, though a design that depends on a lucky seed is fragile and should be improved in the source.

Looking inside with Yosys

Beyond stat, Yosys lets you view the design at each stage. The show command writes a graph of the netlist that Graphviz can display, which is helpful for small blocks. The ltp command reports the longest topological path in the logic, a rough estimate of depth before place and route. Running the passes by hand, for example proc; opt; fsm; memory; techmap, teaches what each does, and the help command inside the Yosys prompt lists every pass with its options.

For a state machine, the log from the fsm pass tells you whether Yosys recognised and recoded it. For a memory, the memory_bram messages tell you whether it became block RAM. Reading these log sections once for a small design builds the habit of checking them for a large one.

Beyond the basics: what the open flow supports

The open toolchain's coverage varies by family, and you should check the current state of each project before choosing a chip.

FamilySynthesisPlace and routeBitstreamMaturity
Lattice iCE40 (LP, HX, UP5K)Yosysnextpnr-ice40IceStormWell established
Lattice ECP5Yosysnextpnr-ecp5TrellisWell established
Lattice Nexus (CrossLink-NX, Certus-NX)Yosysnextpnr-nexusProject OxideUsable, smaller community
Gowin LittleBee and AroraYosysnextpnr-himbaechelApiculaActive, growing
Xilinx 7-seriesYosysnextpnr-xilinx or VPRProject X-RayExperimental, more effort
Intel CycloneYosysnone openPartial researchUse Quartus

Not every feature of a chip is supported. Hard blocks such as DSP multipliers, high-speed serial transceivers, DDR memory interfaces and some clocking resources may be missing or partial. Check the architecture's documentation for the feature you need before relying on it.

Inside Yosys: what synthesis actually runs

The command synth_ice40 is a script of smaller passes, and knowing the sequence explains many log messages. You can print the full list with help synth_ice40 at the Yosys prompt. The stages, in order, are roughly these.

Front end. read_verilog parses the source into an abstract syntax tree and converts it into Yosys's internal representation, RTLIL, a register-transfer-level netlist of processes, cells and wires. Each always block becomes a process, an abstract object describing "this signal gets this value under these conditions".

Process conversion. The proc pass turns processes into real cells. A clocked process becomes flip-flop cells, and a combinational one becomes multiplexers and logic. This is the stage that reports Latch inferred, because a combinational process with an unassigned path converts into a latch cell. Everything after this operates on cells, not on your source text.

Optimisation and coarse-grain mapping. The opt family removes constants, merges identical cells and deletes unused logic. fsm detects state machines and may recode them. memory finds arrays and decides which become dedicated memory cells. alumacc merges adders, comparators and subtractors into arithmetic units, which are later mapped efficiently.

Technology mapping. techmap converts the generic cells into fine-grain gates. For iCE40, arithmetic goes to the carry primitive SB_CARRY together with lookup tables, memories go to SB_RAM40_4K, and flip-flops go to the SB_DFF family, whose variants differ in reset and enable behaviour.

Logic optimisation with ABC. The remaining combinational gates go to the ABC program, which restructures them and maps them onto four-input lookup tables, SB_LUT4. This is where logic depth and LUT count get decided. The -abc9 option selects a newer flow that takes timing into account, and the -retime option lets it move registers across logic to balance paths. Both are worth trying when a design misses timing, and both can change behaviour in ways worth re-testing.

Back end. write_json produces the netlist that nextpnr reads, and stat prints counts.

Because each pass logs what it does, running Yosys without -q for one build is educational. The memory pass, in particular, prints a line for every array and says whether it was mapped to block RAM, which answers one of the most common questions.

Inside nextpnr: placement, routing and timing

nextpnr does three jobs in sequence, and each has settings you can influence.

Packing. Before placement, it groups cells that must sit together. On the iCE40, a lookup table, a carry cell and a flip-flop share one logic cell, and the packer joins a LUT with the flip-flop it feeds when it can. This reduces utilisation and wiring.

Placement. The placer assigns each packed cell to a location. nextpnr offers an analytic placer, called HeAP, which solves for good positions by treating the design as a system of springs and then legalises them, and a simulated annealing placer, which makes random moves and keeps improvements. Both are timing-driven: they favour short wires on paths that are close to missing the target. The --placer option chooses between them for architectures that offer both.

Routing. The router connects each placed cell's outputs to its sinks through the chip's routing graph, a very large graph whose nodes are wires and whose edges are programmable switches. It negotiates congestion: when two signals want the same wire, the router raises that wire's cost and re-routes, until every net has a conflict-free path. The --router option selects between implementations, and the second generation is often faster on large designs.

Timing analysis. After routing, nextpnr adds up the delays along every path between registers, using delay values stored in the chip database. It reports the slowest path for each clock domain, with a breakdown of cell and wire delays. A critical path is the path with the least slack, meaning the least difference between the time a signal needs and the time it has.

Two options are worth knowing from the start. --seed N changes the random starting point of placement, and --freq F sets the target clock in megahertz. For a design with slack to spare, neither matters. For a design near its limit, they decide whether the build passes.

What a bitstream is

An iCE40 bitstream is a sequence of configuration bits grouped by tile. Every logic cell has bits that define its lookup table contents, whether its flip-flop is used and what kind, and which carry mode applies. Every routing switch has bits that connect or disconnect wires. Every I/O cell has bits that set direction, pull-ups and standards. IceStorm's contribution was a database mapping each of these bits to its meaning, built by careful experiments on real chips.

The textual .asc file that nextpnr-ice40 writes is a human-readable dump of those bits per tile, with section headers such as .logic_tile followed by coordinates and rows of ones and zeros. icepack converts it to a compact binary file, and iceunpack goes the other way, which is useful for inspecting a bitstream. The ECP5 flow uses a similar textual configuration, then ecppack writes the binary. Reading these files is rarely necessary, but their existence is why the flow is transparent: every stage's output is a file you can look at.

Constraints in detail

Pin files

A PCF line for iCE40 has the form set_io [options] port pin. Two options are common. -pullup yes enables the internal pull-up resistor on an input, so a button that connects to ground when pressed reads high when released without an external resistor. --warn-no-port suppresses the warning for a constraint whose port does not exist in the design, useful when sharing one pin file among several designs.

board.pcfText
set_io clk 35
set_io -pullup yes btn 10
set_io led_r 11
set_io led_g 37

An LPF file for ECP5 offers more control per pin. IO_TYPE selects the standard, such as LVCMOS33, PULLMODE selects a pull-up, pull-down or none, and DRIVE sets the output current:

board.lpfText
LOCATE COMP "btn" SITE "D6";
IOBUF PORT "btn" IO_TYPE=LVCMOS33 PULLMODE=DOWN;
LOCATE COMP "led" SITE "B2";
IOBUF PORT "led" IO_TYPE=LVCMOS33 DRIVE=8;

The right values come from the board's schematic and the chip's datasheet. A pin set to the wrong electrical standard can fail to work or, worse, damage something, so treat this file with the same care as a hardware design.

Clocks and the global network

An FPGA has a small number of low-skew global clock networks. nextpnr assigns a global buffer to a signal that drives many flip-flop clock pins, and the utilisation report lists the count under SB_GB on iCE40. A design that makes a clock from logic, for example a divided signal feeding another block's clock input, usually works but defeats this, and the router may need a slow general-purpose route. Use a clock enable on one fast clock instead of a derived clock, as the first guide in this cluster explains.

Simulating the synthesised design

RTL simulation checks your intent. Post-synthesis simulation checks what the tools built from it, and it catches mismatches such as an unintended latch or an unsupported construct that synthesis interpreted differently. Yosys writes the mapped netlist back as Verilog:

Shell
yosys -q -p "read_verilog blink.v; synth_ice40 -top blink; write_verilog -noattr blink_syn.v"
iverilog -o blink_syn.vvp blink_syn.v blink_tb.v $(yosys-config --datdir)/ice40/cells_sim.v
vvp blink_syn.vvp

The cells_sim.v file supplies behavioural models of the iCE40 primitives such as SB_LUT4 and SB_DFF, so the simulator knows what the netlist's cells do. The testbench is the same one used for RTL simulation. If the two simulations print different output, you have found either a bug in the design that RTL simulation hid, such as a read of an uninitialised register, or a tool limitation, and both are worth knowing about before you go to hardware.

Debugging on the board

Once a design builds and loads, a board that does not behave needs a methodical approach, because there is no debugger. These techniques, roughly in order of cost, cover most cases.

  1. Make an LED show a fact. Route a signal to an LED: the clock divided down, the reset, a state bit or a "reached state X" flag. Binary questions such as "is the clock running?" and "did the machine leave idle?" get answered in seconds.

  2. Use the serial port. If the board has a USB serial bridge, a UART transmitter in the design can print status bytes, and a terminal program shows them. This turns the FPGA into something that can talk.

  3. Probe pins with an oscilloscope or a logic analyser. Bring internal signals to spare header pins. Place and route will keep a signal only if it drives an output, so a probe signal must go to a constrained pin.

  4. Use an internal logic analyser. Cores exist that record signals into block RAM when a trigger fires and then send the capture over a serial or JTAG link. They cost memory and logic but see inside the chip.

  5. Compare with simulation. Drive the board with the same stimulus as the testbench, and look for the first divergence.

Always check the boring causes first: the board is powered and the right bitstream was loaded, the clock pin is correct, the reset polarity matches the code, and the pin standard matches the voltage.

A catalogue of common errors

  • ERROR: Unable to find a pin or site named ... in nextpnr means a pin name in the constraint file is not valid for the chosen package. Check the --package option first.

  • ERROR: IO 'x' is unconstrained or a warning that a port has no location points to a missing line in the pin file.

  • ERROR: Failed to place cell appears when the design uses a resource the chip lacks or more than it has, such as too many global buffers or block RAMs.

  • Timing FAIL with a very low frequency usually means a long combinational path, such as a wide comparison or a multiplier built from lookup tables, which needs pipelining.

  • A programmer that cannot find the device often means a missing USB permission rule or the wrong cable or board name for the loader.

  • A design that loads but whose LED never changes is, nine times in ten, a wrong clock pin, a reset held active or a polarity error.

Choosing a first board

The table lists boards commonly used with the open toolchain, with the chip family and what each suits. Specifications come from the manufacturers' documentation, and availability changes, so check current listings.

BoardFPGA familyGood for
iCEstickiCE40 HX1KSmallest start, a few LEDs, USB programming
iCEBreakeriCE40 UP5KSoft CPU experiments, PMOD ecosystem, DSP blocks
iCE40-HX8K breakoutiCE40 HX8KMore logic, many pins
ULX3SECP5Large designs, video output, SD card, many peripherals
OrangeCrabECP5Small form factor, DDR3, USB
Colorlight boardsECP5Low cost, for experiments with external wiring
Tang Nano 9KGowinVery low cost, HDMI, via Apicula

A first board with a clear schematic, a USB programmer on board and a community of examples matters more than raw size. The iCEBreaker and the ULX3S have both, and a design written for one is easy to move to the other, with changes limited to the constraint file and the clock rate.

Habits of people who use these tools well

People who build with these tools every week share several habits. They keep a Makefile in every project, so a build is one command. They read the Yosys statistics after every synthesis, which catches a mapping mistake in seconds. They put a clock frequency on every nextpnr run, so a timing failure is a visible failure and not a surprise on the bench. They simulate with a self-checking testbench before programming. They keep each experiment in its own directory with the tool versions recorded. And they read the logs, because the logs are where the tools explain themselves.

A worked timing failure

Suppose a design that accumulates samples fails timing at 48 MHz with the report ending FAIL at 48.00 MHz. The critical path listing names a source register, a destination register and a long chain of stages between them. The workflow for reading it is the same every time.

First, find the endpoints. They tell you which part of the design is slow: an accumulator, an address decoder, a comparator. Second, look at how the delay splits between logic and routing. On iCE40 each lookup table stage costs a fixed amount, and each routing hop between blocks costs more, often most of the total. A path with eight stages of logic and routing between them is a path with a structural problem, not a placement problem. Third, ask what the path computes and whether it needs to finish in one cycle.

The usual remedy is pipelining: split the long path into two shorter ones by inserting a register in the middle. A comparison of two 24-bit counters, for example, can be split into two 12-bit comparisons whose results are registered and then combined on the next cycle. The function is the same and the result arrives one cycle later, which the rest of the design must accept. A second remedy is to reduce what the path does: replace a wide equality test by a test against a constant that the synthesiser can simplify, or replace a multiplication by a shift when a power of two will do. A third is a different encoding, such as one-hot for a state machine whose decoding forms the critical path.

What not to do is raise the target and hope. The tools will not make the logic shallower on their own, and re-running with other seeds only helps when the miss is a few percent. The next posts in this cluster show a full worked example of closing timing from a nextpnr report.

Why the flow is built from small programs

The Unix habit of small cooperating tools is deliberate in this ecosystem, and it brings practical benefits that a monolithic suite cannot. Each stage reads and writes a documented file, so you can substitute any stage. Researchers swap in different placers and routers, and teams add a custom pass between synthesis and place and route. A build can stop at any stage for inspection, and a failure is easy to localise because each program does one thing and reports its own errors.

The cost is that you assemble the flow yourself and keep the versions compatible. Yosys, nextpnr and the chip databases are released on their own schedules, and a very new Yosys may emit a netlist feature that an older nextpnr cannot read, or the reverse. The OSS CAD Suite avoids the problem by shipping a tested set together, which is one of the best reasons to start from it.

What this guide leaves for the later posts

This guide gives the whole map, and each later post takes one road in detail. A hands-on iCE40 build explains each file produced along the way. An ECP5 post covers the LPF format and loader choices in more depth. A post on what synthesis, place and route and bitstreams are goes under the surface of each step. Further posts cover pin constraints, the vendor flows for Xilinx and Intel devices, timing closure, resource reduction, PLLs, constraints for clocked designs, the fabric itself and automation. Read them in order the first time, and use them as references afterwards.

When to use a vendor tool instead

The open flow is excellent for learning, small and medium designs, automation and reproducible builds. A vendor tool is the better choice in some cases.

  • A device the open tools do not support, such as most Intel and the larger Xilinx families.

  • Features that need vendor IP, such as PCIe, multi-gigabit transceivers, DDR controllers or some DSP blocks.

  • Timing closure on a very demanding design, where the vendor's placer has more mature optimisation.

  • Certification or formal requirements that specify a qualified tool.

  • Debug features such as vendor logic analyser cores.

The next posts in this cluster cover Vivado and Quartus builds, so you can use them where needed. Many people use both: open tools for fast iteration on small devices, and a vendor tool for the final product build.

Automating the build

A Makefile turns the four commands into one. It lets the tools re-run only what changed:

makefile
TOP     = blink
PCF     = $(TOP).pcf
FREQ    = 12

all: $(TOP).bin

$(TOP).json: $(TOP).v
	yosys -q -p "read_verilog $<; synth_ice40 -top $(TOP) -json $@"

$(TOP).asc: $(TOP).json $(PCF)
	nextpnr-ice40 --up5k --package sg48 --json $< --pcf $(PCF) --asc $@ --freq $(FREQ)

$(TOP).bin: $(TOP).asc
	icepack $< $@

prog: $(TOP).bin
	iceprog $<

clean:
	rm -f $(TOP).json $(TOP).asc $(TOP).bin

.PHONY: all prog clean

make builds the bitstream, make prog flashes it, and make clean removes the products. The tabs before each recipe line are required by Make. Because every stage is an ordinary command with files as inputs and outputs, the same flow runs unchanged in a continuous integration job, and a later post in this cluster builds that.

Verifying before you flash

Flashing a board is quick, but a good habit is to simulate first, since the iteration time of a simulation is far shorter than a place-and-route run. A reasonable routine for each change is:

  1. Simulate the module with its testbench and check the printed results.

  2. Run synthesis alone and read the Yosys log for latches, width warnings and the cell statistics.

  3. Run place and route and check the utilisation and timing report.

  4. Only then program the board.

For designs of any size, formal verification with SymbiYosys adds a fifth step that proves properties rather than sampling them. It reads the same Verilog and your assertions, and uses solvers to prove or disprove them.

A second example: a counter with a button

To see constraints and an input, extend the design with a button that holds the counter in reset. The button is asynchronous, so the design passes it through a synchroniser, as covered earlier in this cluster.

blink_btn.vverilog
module blink_btn (
    input  wire clk,
    input  wire btn,
    output wire led
);
    reg [1:0]  sync = 2'b00;
    reg [23:0] counter = 24'd0;

    always @(posedge clk) begin
        sync <= {sync[0], btn};
        if (sync[1])
            counter <= 24'd0;
        else
            counter <= counter + 24'd1;
    end

    assign led = ~counter[23];
endmodule

The two-bit shift register is the synchroniser. When the synchronised button is high the counter clears, and the LED stays in the state of bit 23 at zero, which is lit because of the inversion. The pin file gains a line for the button, set_io btn 10 on an iCEBreaker whose user button sits on that pin, again to be checked against the schematic. The build commands do not change. The only new risk is a floating or wrongly polarised input, so check the button's electrical behaviour, whether it pulls high or low when pressed, in the schematic.

Reproducible environments

For a team or a long-lived project, pin the tool versions. The OSS CAD Suite releases are dated, and you can record the date used by a project. A container image or a script that downloads a named release gives every developer and every CI run the same tools. Mismatched versions are the main reason a design that met timing on one machine fails on another, since placement algorithms change between releases.

Record, along with the version, the seed and the command line, in the build log. When timing is tight, the exact combination decides the result, and a build that cannot be reproduced cannot be debugged.

A learning path

A sensible order through this cluster, starting from this guide:

  1. Build and flash the blinking LED for an iCE40 board, as in the next post.

  2. Build for an ECP5 board.

  3. Learn what synthesis, place and route and bitstreams really are.

  4. Write pin constraints in PCF and LPF files.

  5. Move to Vivado and Quartus for the vendor side.

  6. Use the timing reports to raise the clock frequency.

  7. Read synthesis reports to cut resource use.

  8. Learn timing constraints, then the fabric structure behind them.

  9. Automate the whole flow with Makefiles and continuous integration.

Also inToolchains
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.