Lattice MachXO2 Breakout Board HelloWorld with Diamond

Lattice offers a cheap and simple development board for their MachXO2 FPGA. It's just a breakout board with an FPGA, a couple voltage regulators, and an FTDI FT2232 to handle the JTAG stuff. The board is around $25 - $30 from the usual suppliers (Mouser, DigiKey, etc.) This post is my collection of notes for the Lattice Diamond toolchain. I'll cover the basics of setting up a project, simulating it, programming it to Flash or SRAM, and introduce the embedded logic analyzer tool. To keep this post reasonably short, the project is intentionally trivial. A counter is created and setup to only count up when the user holds down a push button. The 8 MSbits of the count are displayed on the 8 LEDs of the development board.

Some Useful Links
Product page for the development board.
Product page for the MachXO2 FPGA
User's Guide for the development board. It has the schematic, BoM, and a general explanation of the board.
Lattice Diamond (IDE) product page. You'll need to register with Lattice. It's free. Register with a valid e-mail address because they email your license file.
Lattice Diamond 3.6 Tutorial. A great introduction that walks you through the basics of the IDE.
Lattice Diamond 3.6 User's Guide.
Lattice Reveal 3.6 User's Guide. Reveal is their embedded logic analyzer tool.
Lattice MachXO2 datasheet. It covers the usual stuff: the family of chips, what's possible, overview of how things work, electrical characteristics, timing, etc.
Lattice MachXO2 sysCLOCK PLL Design and Usage Guide. You'll need to instantiate the internal RC oscillator for most projects, and that's covered on pages 28-30.

There are lots of other useful documents, but the ones linked above will get things started. Be sure to check out the Documentation sections on the MachXO2 and Diamond product pages.

Install Lattice Diamond

  1. Download Diamond from the link above. Run the installer and let it install all drivers.
  2. Open Diamond. The first time you launch it, there will be two errors regarding a missing license file. Click OK both times.
  3. When the License Debug window pops up, go to the License Information tab. Note your NIC ID near the bottom of that tab.
  4. Go to and enter your NIC ID (without the colons between bytes.)
  5. Close the License Debug window by clicking OK.
  6. A "license.dat" file will be emailed to you, place it inside C:\lscc\diamond\3.6_x64\license
  7. Restart your PC. Yes, this really seems to be required. If you don't, Diamond will repeatedly fail to find the license file.

Create a New Project

  1. Open Diamond.
  2. Create a new project:
    File > New > Project Next > give it a name and choose a better project location > Next > Next Pick your device. The XO2 Breakout Board has a LCMXO2-7000HE-4TG144C Next > Next > Finish

Write the Code

  1. Create a top file:
    File > New > File Verilog Files > name it "top" > New
  2. Write some code:
    module top (leds, pushbutton); output wire [7:0] leds; input wire pushbutton; wire fpga_clock; OSCH #(.NOM_FREQ("133.00")) rc_oscillator(.STDBY(1'b0), .OSC(fpga_clock)); slow_counter counter(.clock(fpga_clock), .enable(pushbutton), .output_byte(leds)); endmodule module slow_counter (clock, enable, output_byte); input wire clock; input wire enable; output reg [7:0] output_byte; reg [31:0] counter; initial begin output_byte = 8'b11111111; counter = 32'b0; end always @(posedge clock) begin if(enable == 1'b1) begin counter <= counter + 1'b1; output_byte <= ~counter[31:24]; end end endmodule
  3. Synthesize the code to make sure there are no errors. A green checkmark indicates success.
    Process tab > double-click on Synthesize Design


  1. Create a testbench file:
    File > New > File Verilog Files > name it "testbench" > New
  2. Write some code that simulates a user holding down the pushbutton for one second:
    `timescale 1 ns / 1 ns module testbench; reg pushbutton; wire [7:0] leds; top dut(.leds(leds), .pushbutton(pushbutton)); initial begin pushbutton = 0; #1000000000 // 1s pushbutton = 1; #1000000000 // 1s pushbutton = 0; #1000000000 // 1s $finish; end endmodule
  3. Mark top.v for "synthesis and simulation" and mark testbench.v for "simulation"
    File List > impl1 > Input Files > top.v > right-click > Include for > Synthesis and Simulation File List > impl1 > Input Files > testbench.v > right-click > Include for > Simulation
  4. Run the simulation. It will take a while to run because three seconds of time will be simulated. Most simulations run for just a few microseconds, but this is a long run due to the intentionally slow behavior of the LEDs.
    Tools > Simulation Wizard Next > give it a name > Next > Next > Next > Next > Finish Aldec Active-HDL will run but defaults to pausing the simulation after 1us. Simulation > Run > OK
  5. Zoom the waveform to see all of it. Observe the LEDs slowly changing over time. Note that it looks like a count-down but in real life it will look like a count-up because the LEDs are wired active-low on the PCB.
    Waveform > Zoom to Fit

Assign Pins and Generate the Bitstream File

  1. Re-synthesize the code.
    Process tab > double-click on Synthesize Design
  2. Open the Spreadsheet View and assign pin numbers:
    Tools > Spreadsheet View Assign the "leds" nets to the pins for the LEDs. (Pin numbers are on page 13 of the dev board user guide.) Assign the "pushbutton" net to pin 3.
  3. If you want to look at reports, enable the ones you want:
    Process tab > Map Design > check "Map Trace" Process tab > Place and Route Design > check "Place and Route Trace" Process tab > Place and Route Design > check "I/O Timing Analysis"
  4. Generate a "JEDEC File" if you want to program to flash, and/or generate a "Bitstream File" if you want to program to SRAM.
    Process tab > Export Files > check "JEDEC File" Process tab > Export Files > check "Bitstream File" Double-click on Export Files. This will generate the files and perform all prerequisite functions.

Program to Flash or SRAM

  1. Program to flash:
    Tools > Programmer Detect Cable Pick the "...Lattice FTUSB Cable Interface A..." device > OK Device = "LCMXO2-7000HE" File Name = your .jed file (The .jed file will be in the "impl1" folder inside your project folder.) Design > Program
  2. Optionally change to SRAM programming mode:
    Double-click below "Operation" Access Mode = Static RAM Cell Mode Operation = SRAM Erase, Program, Verify Programming File = your .bit file (The .bit file will be in the "impl1" folder inside your project folder.) OK Design > Program

Embed a Logic Analyzer

  1. Open Reveal Inserter and specify what signal(s) to "probe" and specify what signal will clock the logic analyzer. I'm probing the counter's enable signal (the pushbutton) and the counter's internal 32bit count. I'm clocking the logic analyzer with the 133MHz FPGA clock.
    Tools > Reveal Inserter Drag-and-drop any signals you want to probe from the Design Tree over to the Trace area of the Trace Signal Setup tab. Drag-and-drop your clock signal over to the Sample Clock box of the Trace Signal Setup tab.
  2. Specify what signal(s) to trigger off of in the Trigger Unit section. Specify a trigger expression in the Trigger Expression section. I'm triggering off of a rising edge on the counter's enable signal. I don't need a complicated expression, so I just specify the trigger unit as the expression.
    Click on the Trigger Signal Setup tab In the Trigger Unit area: Double-click below Signals Choose the counter's enable signal, click the ">" button, click OK Set Operator to Rising Edge Set Value to 1 In the Trigger Expression: Set Expression to TU1
  3. Check for errors, then embed the logic analyzer into the project:
    Debug > Design Rule Check Look at the Output tab at the bottom of the window for "Design Rule Check PASSED." Debug > Insert Debug OK > Specify a filename for the Reveal project > Save
  4. Re-generate the JEDEC and/or Bitstream files, then re-program the FPGA:
    Double-click on "Export Files" in the Process tab. Tools > Programmer Design > Program

Use the Logic Analyzer

  1. Open and setup Reveal Analyzer:
    Tools > Reveal Analyzer Click "Create A New File" > give it a name Click "Detect" Click "Scan" Click "Browse" > pick the .rvl file you saved earlier > OK OK
  2. Start the logic analyzer:
    Click the Run icon (looks like a play symbol) next to Ready "Ready" will change to "Connecting" then "Running" It's now waiting for a trigger. Press the pushbutton to trigger it.
  3. You can zoom the waveform with Ctrl-scrollwheel.
  4. You can change the radix of a multi-bit signal by clicking in the Data column.
  5. You can re-arm the logic analyzer by clicking the Run icon (play symbol) again.

YouTube Video

FTDI SPI Tutorial: LibMPSSE with Visual Studio 2015

FTDI is mostly known for their USB UART chips, but some of their higher-end ICs also have an “MPSSE” (multi-protocol synchronous serial engine) that can do SPI, I2C and JTAG. I made a YouTube video tutorial covering the basics of their SPI library for C. I thought I'd also write this post to summarize that video and provide its content in text form for easier referencing.

FTDI sells a ready-made USB adapter, it's part number C232HM-DDHSL-0. You can buy it from the usual suppliers (Mouser, DigiKey, etc.) for around $26 + shipping. It's essentially an FT232H broken out to 10 wires with female 0.1” connectors.

Some Useful Links
The product page for this USB adapter and some other ones.
The D2XX driver you'll need to install. Windows will automatically install the VCP driver (UART driver) when you plug the cable in, but you need to manually install this D2XX driver if you want to use the cable for SPI/I2C/JTAG projects.
The datasheet for this USB adapter. It's got the schematic, a brief summary of what's possible, and tells you which color wire is used for what.
An App Note that provides a HelloWorld-level demo of their SPI library for C. It's a useful document, but their code isn't as clear as I'd like. They also did things the hard way (declaring a bunch of function pointers for the DLL) which is not needed if you will be using Visual Studio.
The User Guide for their SPI library for C. It documents all of the functions and data structures.
The actual library and a simple demo project. This ZIP file contains the headers and the .lib file you will need to copy into your project.

Prepare a Visual Studio 2015 Project

  1. Open Visual Studio 2015, then create a new project:
    File > New > Project Templates > Visual C++ > Win32 Console Application Give the project a name, then click OK In the Application Wizard: click Next, then uncheck "Precomiled Header", then click Finish
  2. Remove some unneeded files from the project: stdafx.h, targetver.h, and stdafx.cpp
    In the Solution Explorer, right-click over each of those files > Remove > Delete
  3. Copy four files from FTDI's LibMPSSE-SPI zip file (linked above) into the Visual Studio project: ftd2xx.h, libMPSSE.lib, libMPSSE_spi.h, and WinTypes.h
    Those files are in > LibMPSSE-SPI > Release > samples > SPI > SPI Copy those four files into your Visual Studio project's folder. By default, that would be in: This PC > Documents > Visual Studio > Projects > YourProjectName > YourProjectName
  4. Tell Visual Studio about those four recently added files:
    In the Solution Explorer, right-click on Header Files > Add > Existing Item Select ftd2xx.h, libMPSSE_spi.h, and WinTypes.h, then click Add In the Solution Explorer, right-click on Resource Files > Add > Existing Item Select linMPSSE.lib, then click Add
  5. Fix an error in WinTypes.h: Replace "sys/time.h" with "time.h"
    Change line 5: Before: #include <sys/time.h> After: #include <time.h>

Minimalist Demo Program

By now the Visual Studio project is fully setup. You can starting using the API. Below is a simple demo program I wrote. It's communicates with an SPI gyroscope and displays X/Y/Z velocities on screen.

  1. The program starts by displaying information about each MPSSE "channel" that is available. An MPSSE channel is the part of the IC that can do SPI/I2C/JTAG protocols. Some FTDI ICs are UART-only, so they won't have any MPSSE channels. The USB adapter I'm using has one MPSSE channel. Some of their more advanced ICs have two MPSSE channels.
  2. The user will be asked to specify which MPSSE channel to use.
  3. The program will prepare that channel for SPI Mode 0 with a 1 MHz clock.
  4. The SPI gyro will be configured by writing to five of it's registers.
  5. Finally, an infinite loop is used to poll the gyro's X/Y/Z velocity registers. Those velocities are formatted and printed to the screen.
  6. The program can be closed by pressing Ctrl-C.
There are 1 channels available. Channel number: 0 Description: C232HM-DDHSL-0 Serial Number: 1637980 Enter a channel number to use: 0 x = -182, y = -395, z = -1157 x = -50, y = -14, z = -276 x = -351, y = -159, z = -1936 x = -211, y = -293, z = -190 x = -217, y = -310, z = -200 x = -232, y = -329, z = -177 x = -216, y = -301, z = -185 x = -239, y = -329, z = -167 x = -211, y = -304, z = -185 x = -215, y = -307, z = -209 x = -234, y = -285, z = -189 ...

Source Code

// red wire = 3v3 // black wire = ground // orange wire = sclk // yellow wire = mosi // green wire = miso // brown wire = cs #include <stdio.h> #include <Windows.h> #include "libMPSSE_spi.h" // a helper function for showing fatal error messages void print_and_quit(char cstring[]) { printf("%s\n", cstring); getc(stdin); exit(1); } int main(int argc, char **argv) { Init_libMPSSE(); FT_STATUS status; FT_DEVICE_LIST_INFO_NODE channelInfo; FT_HANDLE handle; // check how many MPSSE channels are available uint32 channelCount = 0; status = SPI_GetNumChannels(&channelCount); if (status != FT_OK) print_and_quit("Error while checking the number of available MPSSE channels."); else if (channelCount < 1) print_and_quit("Error: no MPSSE channels are available."); printf("There are %d channels available.\n\n", channelCount); // print out details for each MPSSE channel for (int i = 0; i < channelCount; i++) { status = SPI_GetChannelInfo(i, &channelInfo); if (status != FT_OK) print_and_quit("Error while getting details for an MPSSE channel."); printf("Channel number: %d\n", i); printf("Description: %s\n", channelInfo.Description); printf("Serial Number: %d\n", channelInfo.SerialNumber); } // ask the user to select a channel uint32 channel = 0; printf("\nEnter a channel number to use: "); scanf_s("%d", &channel); // open the MPSSE channel (get the handle for it) status = SPI_OpenChannel(channel, &handle); if (status != FT_OK) print_and_quit("Error while opening the MPSSE channel."); // init the channel (configure it) ChannelConfig channelConfig; channelConfig.ClockRate = 1000000; // 1 MHz channelConfig.configOptions = SPI_CONFIG_OPTION_MODE0 | SPI_CONFIG_OPTION_CS_DBUS3 | SPI_CONFIG_OPTION_CS_ACTIVELOW; channelConfig.LatencyTimer = 75; status = SPI_InitChannel(handle, &channelConfig); if (status != FT_OK) print_and_quit("Error while initializing the MPSSE channel."); // configure the gyro uint8 tx_buffer[6] = { 0x20 | (1 << 6) | (0 << 7), // first register is 0x20, bit6 high for auto-increment mode, bit7 low for write mode 0b01111111, // value for register 0x20 0b00101001, // value for register 0x21 0b00001000, // value for register 0x22 0, // value for register 0x23 0 // value for register 0x24 }; uint32 transferCount = 0; uint32 options = SPI_TRANSFER_OPTIONS_SIZE_IN_BYTES | SPI_TRANSFER_OPTIONS_CHIPSELECT_ENABLE | SPI_TRANSFER_OPTIONS_CHIPSELECT_DISABLE; status = SPI_Write(handle, tx_buffer, 6, &transferCount, options); if (status != FT_OK) print_and_quit("Error while configuring the gyro."); // enter an infinite loop that reads X/Y/Z velocities from the gyro while (1) { uint8 tx_buffer[7] = { 0x28 | (1 << 6) | (1 << 7), // first register is 0x28, bit6 high for auto-increment mode, bit7 high for read mode 0, // read register 0x28 0, // read register 0x29 0, // read register 0x2A 0, // read register 0x2B 0, // read register 0x2C 0 // read register 0x2D }; uint8 rx_buffer[7] = { 0 }; uint32 transferCount = 0; uint32 options = SPI_TRANSFER_OPTIONS_SIZE_IN_BYTES | SPI_TRANSFER_OPTIONS_CHIPSELECT_ENABLE | SPI_TRANSFER_OPTIONS_CHIPSELECT_DISABLE; status = SPI_ReadWrite(handle, rx_buffer, tx_buffer, 7, &transferCount, options); if (status != FT_OK) print_and_quit("Error while reading from the gyro."); int16 x = (rx_buffer[2] << 8) | rx_buffer[1]; int16 y = (rx_buffer[4] << 8) | rx_buffer[3]; int16 z = (rx_buffer[6] << 8) | rx_buffer[5]; printf("x = %+6d, y = %+6d, z = %+6d\n", x, y, z); } // this code will never be reached due to the infinite loop above, but you would normally want to end with this: Cleanup_libMPSSE(); return 0; }

YouTube Video

Servo Tester / 2.4GHz Spectrum Analyzer / Tetris Firmware

As promised in my previous post about this servo tester / spectrum analyzer / tetris implementation, I have uploaded the source code to my Servo Tester repository on GitHub. Check out the photos in that previous post if you'd like to see the work as it progressed over a few months of code refactoring and feature additions. I made a brief video clip to demonstrate the features of the firmware:

Servo Tester / 2.4GHz Spectrum Analyzer / Tetris

Back in 2012 I started working with the STM32 line of microcontrollers and my first big project was a servo tester. That project worked out great and the tool I made has been in use for the last two years. Recently I decided to update the project and expand upon it. I added a color LCD with touchscreen, voltage and current sensing, a 2.4GHz spectrum analyzer, and for fun I decided to implement a simple version of Tetris. The end result:

It took quite a bit of work to get this project done. The prototype was a mess of jumper wires and breakout boards. I also started out with push buttons for the user interface but switched to using the touchscreen in an effort to keep things simple.

Here's a short video clip of me testing the Tetris game:

This project marked the first time I have ever had a PCB professionally fab'd. I was very relieved and pleased when everything worked perfectly with the first PCB revision. After I got the PCBs in the mail I checked them over, assembled one board, flashed the firmware... and it worked!

I bought a project box, Dremel'd and filed it to shape, then hot glued the electronics in place:

I'll post a video clip and the firmware within the next day or two.

A Complete STM32F0 Development Environment

This post expands on (and updates) a few of my earlier posts about developing for the STM32F0 microcontroller. Some parts have become easier and I've found a few more useful ways to get things done. Some of the commands below assume a Debian-based Linux distribution, but should be reworkable for your particular setup.

Let's start by making some directories for the STM32 tools and projects:

$ mkdir ~/stm32 $ mkdir ~/stm32/projects

Installing the Toolchain

The GCC ARM Embedded package is a collection of utilities (compiler, assembler, libraries, debugger, etc.) that's maintained by ARM employees. It's available in the regular repositories, but you can use a PPA to get more up-to-date versions. OpenOCD facilitates communication between your PC and the ST-Link programmer. Install both tools:

$ sudo add-apt-repository ppa:terry.guo/gcc-arm-embedded $ sudo apt-get update $ sudo apt-get install gcc-arm-none-eabi libnewlib-arm-none-eabi libnewlib-doc gdb-arm-none-eabi openocd

There's currently a minor bug: those packages don't include the newlib-nano library. If you need newlib-nano you can manually install the GCC ARM Embedded package. Instead of using the above three commands, use these:

$ sudo apt-get install openocd ia32-libs $ cd ~/stm32 $ wget\ gcc-arm-none-eabi-4_8-2014q1-20140314-linux.tar.bz2 $ tar -xjvf gcc-arm-none-eabi-4_8-2014q1-20140314-linux.tar.bz2 $ echo export PATH=$PATH:/home/username/stm32/gcc-arm-none-eabi-4_8-2014q1/bin >> ~/.bashrc $ source ~/.bashrc

Regardless of how you install GCC Arm Embedded, you'll also want the CMSIS and STM StdPeriph libraries:

$ cd ~/stm32 $ git clone $ cd stm32f0-discovery-basic-template/Libraries/ $ make

We're now ready to build and flash some firmware. I'll cover three ways to accomplish that: using the command line, using the Geany IDE, and using the Eclipse IDE.

Building and Flashing: From the Command Line

For a very simple workflow you can just use the command line to get everything done. Write your code in whatever editor you like, and use a Makefile to encapsulate all of the build, debugging and device programming commands.

My basic empty project is available as a zip file or through my stm32f0-empty-project repository on GitHub. Extract it to ~/stm32/projects/. It has a main() that just configures a GPIO and toggles it in an infinite loop. The f0lib/ directory contains my incomplete and unpolished collection of potentially reusable code. There's also a Makefile and configuration files for GDB and OpenOCD. Usage is trivial:

make compiles the firmware into an ELF and a BIN.
make install flashes the firmware to the STM32F0 with OpenOCD.
make clean deletes the ELF and BIN.
make debug_server, make debug_nemiver and make debug_cli are used for debugging. More on this in the debug sections below.

Building and Flashing: With the Geany IDE

Geany is a simple IDE and perhaps my favorite environment for programming in C. The IDE is essentially a text editor with a few extra features to support coding. It's minimalist and very fast. The only settings you need to change are the build commands. Go to Build > Set Build Commands. Configure them as compile = make clean, build = make, execute = make install. While this might sound weird, it makes the three build icons in the toolbar perfect for one-click actions instead of having to use the drop-down build menu.

Side note: if you're using Cinnamon or Gnome3 with a high-DPI display, the experimental GTK3 support in Geany gives you a beautiful high-DPI-friendly IDE. You'll have to build Geany from source with ./configure --enable-gtk3 && make && make install.

Building: With the Eclipse IDE

Many people prefer the Eclipse IDE. While I don't care for it's busy interface and relatively sluggish performance, there is a must-have plug-in that gives awesome annotated register views in the debugger. Start by installing the Eclipse and CDT packages, then install the GNU ARM Eclipse and EmbSysRegView plug-ins. Don't install Eclipse from the repositories -- the repo version of Eclipse is a few years old.

Download from Extract to ~/stm32 Open Eclipse Help > Install New Software > Work with > Kepler Programming Languages > C/C++ Development Tools Help > Install New Software > Add Name = GNU ARM Eclipse Plug-in Location = Select: Cross Compiler Support, Generic Project Templates, STM32Fx Project Templates, OpenOCD Debugging Support Help > Install New Software > Add Name = EmbSysRegView Plug-in Location = Select: embsysregview (both components)

I only use Eclipse for debugging, so you might be better served by reading the GNU ARM Eclipse plug-in documentation. My way is a bit of a dirty hack to just get things working well enough to debug. Here's what I do:

File > New > C Project Executable > Empty Project > Cross ARM GCC > Next > Next Toolchain Path = ~/stm32/gcc-arm-none-eabi-4_8-2014q1/bin Finish Copy the contents of your project folder into the Eclipse project's folder. Then in Eclipse: Right click on project > Refresh Right click on project > Properties C/C++ General > Paths and Symbols > GNU C > Add > File system Navigate to: ~/stm32/stm32f0-discovery-basic-template/Libraries/CMSIS/Device/ST/STM32F0xx/Include OK > OK > Yes Right click on project > Properties C/C++ Build > Build Settings tab Uncheck “Use default build command” Uncheck “Generate Makefile automatically” Build command = make Build directory = ${workspace_loc:/your_project_name_goes_here} C/C++ Build > Behavior tab "Build (incremental build)" = leave it empty

Again: I only use Eclipse for debugging. If you actually want to do any development in Eclipse, don't do what I do.

Debugging: With the Eclipse IDE

Having already prepared your project, now setup the debugging parts:

Right click on project > Debug as > Debug Configurations Double-click on GDB OpenOCD Debugging Name = STM32_Debug Debugger tab Uncheck “Start OpenOCD locally” GDB Client Setup Executable = arm-none-eabi-gdb Apply Close Window > Preferences C/C++ > Debug > EmbSys Register View Architecture = cortex=m0 Vendor = Stmicro Chip = stm32f051x Board = STM32F0DISCOVERY In a terminal in the project directory: make debug_server (Leave this running) Click on the debug drop-down in the toolbar > STM32_Debug > Yes Window > Show View > Other Debug > EmbSys Registers

You can now debug using step/next/etc. Double-click on registers in the EmbSys Registers tab to view their contents. It automatically updates as you step though code.

Debugging: With Nemiver

Nemiver is a fast and no-frills debugger. Using it with this project is trivial:

$ make debug_server $ make debug_nemiver

make debug_server will have to stay running for the duration of the debugging process, so run it in a separate terminal window. After closing Nemiver you can close the server with Ctrl-C.

Debugging: From the Command Line

Command line debugging with this project is also really easy:

$ make debug_server $ make debug_cli

make debug_server will have to stay running for the duration of the debugging process, so run it in a separate terminal window. After closing gdb you can close the server with Ctrl-C.

< Prev  2  Next >