iAchieved.it

Software Development Tips and Tricks

By

I2C with the SiFive HiFive1 Rev B

Hey kids! Today we’re going to take a look at the SiFive HiFive1 Rev B and Freedom Metal I2C API.

I am going to be using a classic EEPROM from National Semiconductor, the NM24C17. The NM24C17 is a 16 kilobit (2K) EEPROM that can be written to and read from using I2C.

If you have one of these EEPROMs lying around (and who doesn’t?) and want to use it with your HiFive1 board, you’ll also need:

  • the datasheet
  • a breadboard
  • breadboard wires
  • 2 4.7k pull-up resistors

What you might also want to have handy a digital logic analyzer such as the Logic 8 from Saleae.

The I2C circuit is a simple one, but it is important to note that the NM24C17 EEPROM does not come with I2C pull-up resistors, so we need to add them in our circuit.

Assembling everything with the HiFive1 I2C pins and providing power.

Reading the Datasheet

When working with I2C devices it is so important to read through the datasheet once or twice. Or ten times. Datasheets can be dense and intimidating, but I have rarely come across an issue I was troubleshooting that didn’t end up being caused by not reading the datasheet closely.

Writing

Okay, let’s start coding some I2C with Freedom Metal. We’ll start with a basic shell.

Working with I2C in Freedom Metal starts with including the <metal/i2c.h> header file and obtaining a pointer to the I2C device with metal_i2c_get_device. For the HiFive1 Rev B board there is only one device to get, and it’s at index 0. Once you have a pointer to the I2C device, initialize it with metal_i2c_init. We’ll configure our device for 100 kbits/sec (I2C “full speed”) and as the master.

Now, let’s look at our first write function, which will be to write a sequence of bytes to the EEPROM at a given address. This code is very specific to the way the NM24C17 EEPROM functions. We will be using the metal_i2c_write function which takes as its arguments:

  • a pointer to the I2C controller device on the RISC-V chip
  • the address of the I2C bus device to talk to
  • the length of the message to send to the bus device
  • the message to send
  • a flag indicating whether or not to send the I2C stop bit

The first argument will be our struct metal_i2c* i2c_device variable, but the address of the EEPROM on the bus is interesting.

At first blush it appears the address would be 0xa0 to account for the first four bits to transmit are 1 0 1 0, and for the NM24C17 device the 3 page address bits appear to be all 0 (appear is the operative word). That leaves us with the R/W bit, which for a write would be 0. 1010 0000b, or 0xa0, right? Wrong. The R/W bit is not a part of the device address here, which leaves us with 1010000b, which is 0x50.

The message to send to the EEPROM consists of two bytes: the memory address in the EEPROM to write to and the value to write. For simplicity we’ll just write the value 0xab at the address 0x00.

The final argument to metal_i2c_write is to indicate whether or not to signal an I2C stop bit upon completion. Since the stop bit is required for us to write this data to the EEPROM we will use METAL_I2C_STOP_ENABLE.

One thing I’ve found to be true about I2C is that if it works, it works. If it doesn’t, you better have a digital logic analyzer on hand to look at things.

Reading

Now let’s read the data that we wrote back in. This requires two function calls: metal_i2c_write and metal_i2c_read.

Notice above that the first step to reading a byte from the EEPROM is to write out the address to be read from, followed by a read. There is only one stop bit in this sequence:

Notice the use of METAL_I2C_STOP_DISABLE; this instructs the I2C controller not to signal a stop bit at the conclusion of the write.

We make double use of the readbuf array by initializing it to the address in the EEPROM we want to read from, and then to hold the data read in.

Writing and Reading Multiple Bytes

Writing and reading one byte at a time to our EEPROM is a bit tedious, so let’s make use of the multiple-byte write.

In this example we send the device address (again, 0x50 for the EEPROM), followed by an address to write to in the EEPROM, and then up to 16 bytes of data.

Before we get to writing again, I’ve made mention that 0x50 is the I2C device address of the EEPROM. While it is, that isn’t the whole story. That is the address for page block 0 of the device, but it supports 8 page blocks. Selecting the page block is done with the lower nibble of the device address. For example, page block 1 can be addressed at 0x51, page block 2 at 0x52, and so on. Each page block is 2 kilobits, or 256 bytes.

At any rate, let’s stick with page block 0 for now and write 16 bytes:

Of course, we are actually writing 17 bytes out to the EEPROM, the first of which is the address we want to write to.

Reading the data back in can look like this:

A Smarter API

After understanding the basics of reading and writing to the NM24C17 it’s time to write an API to encapsulate the nuts and bolts. Our header file looks like this:

Our structure is arranged such that the addr byte is positioned immediately prior to the buf. This organization allows us to take advantage of the C memory layout of the data and writing to the EEPROM. For example:

Our device address is the base address of the EEPROM (0x50) ORed with the page block number. The length of the message to write is the length of the data buffer the user wants to write plus the address byte. Writing starts at the address byte and continues into the buffer.

Remember the exhortation to read the datasheet, and read it several more times? Here is what happens if you start a write on an address not evenly divisible by 16. Notice that our write address starts at 0x22 in page block 1. Sixteen bytes are presumably written, but when trying to read them back in, the last two bytes read are 0xff. Hmm.

From the National Semiconductor datasheet definitions:

  • PAGE – 16 sequential addresses (one byte each) that may be programmed during a “Page Write” programming cycle.
  • PAGE BLOCK – 2,048 (2K) bits organized into 16 pages of addressable memory. (8 bits) x (16 bytes) x (16 pages) = 2,048 bits”

But wait! The Fairchild-printed version of this EEPROM’s datasheet says a bit more:

To minimize write cycle time, NM24C16/17 offer Page Write feature, by which, up to a maximum of 16 contiguous bytes locations can be programmed all at once (instead of 16 individual byte writes). To facilitate this feature, the memory array is organized in terms of “Pages.” A Page consists of 16 contiguous byte locations starting at every 16-Byte address boundary (for example, starting at array address 0x00, 0x10, 0x20 etc.)

Like I said, always read the datasheet and sometimes you have to read two of them to get the whole story.

Recap

There are four basic functions needed to use I2C with Freedom Metal:

  • metal_i2c_get_device – obtain a pointer to the underlying I2C device on the microcontroller
  • metal_i2c_init – initialize the I2C device speed and mode
  • metal_i2c_write – address and send data on the bus
  • metal_i2c_read – address and read data from the bus

It really is that simple!

Get the Code

I’ve recently start using PlatformIO to develop on my HiFive1. If you haven’t checked it out I recommend you doing so; it’s very easy to install and start making use of your board right away without having to manually download toolchains and JTAG interfaces. I’ve posted a PlatformIO-based project on GitHub for working with the NM24C17.

By

Exploring HiFive1 Rev B GPIOs with PlatformIO

In our last post we looked at the GPIO pins of the SiFive HiFive1 Rev B board, and in this one we will continue doing so, but let’s take a look at PlatformIO on that journey. PlatformIO bills itself as “A new generation ecosystem for embedded development” and aims to really simplify pulling together all of the tools needed for embedded development. In our introduction to the HiFive1 Rev B we outlined all of the packages you needed to install and configure to get started with the board. Cross-compilers, JTAG daemons, remote debug tools, SDKs, and so on. What if we could skip all that, not just for one microcontroller platform, but for hundreds of them? Enter PlatformIO.

Installing PlatformIO

PlatformIO, while compatible with a number of popular editors (Sublime Text, Atom, etc.), really shines with Visual Studio Code. While VSCode has features I don’t find appealing (horizontal bars on my code), it is very configurable and I can turn them off and enable Emacs keybindings. After some time with VSCode and PlatformIO, I really began enjoying how straightforward it was to work with the HiFive1 Rev B.

Installing PlatformIO is simple with Visual Studio Code. Open the Extensions panel and search:

Click on Install. You’ll see a “landing page” of sorts for PlatformIO and a window open up on the bottom indicating it is being installed and configured.

Once PlatformIO is installed we’ll create a project for use with our HiFive1 Rev B board. Click on the PlatformIO Projects button and then Create New Project.

This is where PlatformIO really shines. There are over 800 boards to choose from, and depending on the board, multiple frameworks to work with. For example, with the HiFive1 Rev B you can use either the Freedom E SDK (which we use), or the Zephyr RTOS.

Creating a New File

Obviously we’ll need to write some code, so in your project right-click on src and select New File.

Visual Studio Code will prompt you to name the file in the project explorer; ours is named simply main.c. We’ll do the GPIO equivalent of a Hello World by blinking the onboard green LED:

Building and Uploading

PlatformIO automates and streamlines installation of the correct toolchain, debugger, SDK and so on. To build your project there is a checkmark on the bottom of the editor window; if you hover over it you’ll see the label PlatformIO: Build. Click on it and scroll through the output to see what PlatformIO is doing; I’ve found it very helpful to read everything that is going on.

Uploading your project to the HiFive1 Rev B is as simple as clicking the right arrow that is labeled PlatformIO: Upload. Again, if this is your first time using PlatformIO on a given environment you can see it’s installing what’s necessary to upload to your board.

Here is a great example of what PlatformIO is doing in the background:

While it’s possible to do this by hand (and we have!), how nice it is to have it done automatically for you.

Serial Output

PlatformIO does have the ability to open a serial monitor to your HiFive1 Rev B board, though you may have to do a bit of configuration here. Open the project’s platformio.ini and ensure that your environment configuration has monitor_speed=115200 set. This will tell PlatformIO to use 115200 baud to communicate on the serial port. Then open the serial monitor with the “electric plug” icon and choose the first usbmodem port you see.

I typically prefer to use screen on macOS for this – the console output in Visual Studio Code is nice, but I’m used to screen and like having it in a separate terminal window altogether. For example, typing screen /dev/cu.usbmodemIDENTIFIER 115200 (where IDENTIFIER will be specific to your machine) will bring up the serial console to the board.

Testing the GPIO Pins

Okay, PlatformIO is ready to go and we’re going to take a look at the GPIO pins on the HiFive1 Rev B again. I’ve learned a bit since writing about them in this post. For starters, digital pin 14 on the header is not connected and there is no mapping of a pin from the GPIO device.

In addition, pins 11, 12, and 13 on the header correspond to the MOSI, MISO, and SCK signals for the SPI device; since they are tied to SPI writing a digital one to them has no effect. On the other hand, you can write a 1 to pin 10 (SPI SS) and get an output.

That said, you can use the I2C pins (digital pins 18 and 19) and write a digital one or zero to them as long as we’re willing to give them up as I2C pins.

Pins 15 and 16 are interesting. If you look at the HiFive1 Rev B schematic for J4 (the Arduino 6 pin block on the bottom left of the ESP32) you see GPIO 9 and GPIO10 map to DIG15 and DIG16. But then going over here we see that:

  • GPIO9 is tied to a line labeled SPI_CS2 which comes from the ESP-SOLO-1
  • GPIO10 is tied to a line labeled WF_INT which comes from the ESP-SOLO-1

The schematic notes “Solder across SJ1 to connect GPIO_9 to SPI_CA2” (I think that is a typo). On the physical board I cannot find SJ1 or SJ2, so I’m assuming these connections are present.

So, what does that gives us in the end?

  • DIG2 – easy to use to drive a digital output
  • DIG3 – easy to use to drive a digital output, but doing so interferes with the onboard LED
  • DIG4 – easy to use to drive a digital output
  • DIG5 – easy to use to drive a digital output, but doing so interferes with the onboard LED
  • DIG6 – easy to use to drive a digital output, but doing so interferes with the onboard LED
  • DIG7 – easy to use to drive a digital output
  • DIG9 – easy to use to drive a digital output
  • DIG10 – easy to use to drive a digital output, but doing so interferes with using SPI
  • DIG17 – easy to use to drive a digital output
  • DIG18 – easy to use to drive a digital output, but interferes with I2C
  • DIG19 – easy to use to drive a digital output, but interferes with I2C

In the next post I’m going to be building an I2C circuit that contains 4 EEPROMs, each of which will have the same address. To do so I want to use two digital output pins to specify which I2C chip to work with, so to make life easy I want to choose pins that won’t interfere with anything else. DIG2, DIG4, DIG7, DIG9, and DIG17 are my best bests, and since DIG2 and DIG4 are on the same side of the board I’ll start there.

Conclusion

PlatformIO is pretty damn slick if you ask me and worth checking out if you are just starting with the HiFive1 Rev B. While I still recommend that you understand cross-compilers and the underlying tools that go into supporting such a platform, it really does take the hassle out of downloading and configuring everything!

If you have a HiFive1 Rev B board, try checking out our GPIO project. I have no doubt that you’ll be able to build and upload it with minimal fuss using PlatformIO.

By

HiFive1 Rev B GPIO Pins

Let’s make use of the HiFive1 Rev B schematics to map out the GPIO controller device pins. Of particular interest is sheet 3, and the following components of the schematic in section D1:

We’re going to use this as our starting point. Three GPIO lines labeled 19, 21, and 22 with LEDs on the lines.

Editor’s Note: This write-up on the SiFive HiFive1 Rev B assumes you have one and are familiar with powering it up, connecting to the serial port, and uploading applications. See our last post if you need to orient yourself with the environment.

Using Metal GPIO

If you haven’t done so already, familiarize yourself with Freedom Metal and the API documentation because we’re going to make use of the GPIO functions.

Recall in the schematic above that the onboard LEDs are tied to GPIO 19 (green LED), GPIO 21 (blue LED), and GPIO 22 (red LED). While the Metal LED API could be used here, we’re going to work directly with the GPIO functions to prove to ourselves that the above GPIO pins are correct, and also check out the 8 color combinations the LED can produce.

Our basic loop is going to cycle from 0 to 7 and turning on the red LED if bit 1 is set, the green LED if bit 2 is set, and the blue LED if bit 3 is set. This should cause our HiFive1 on-board LED to cycle through the following color chart:

Okay, let’s get the basics down. The GPIO can be accessed by obtaining a struct metal_gpio* using the metal_gpio_get_device function, like this:

Now that we have the GPIO device itself, let’s enable GPIO 19 as an output pin. In our schematic take note that the other side of the LED is tied to 3.3V. In other words, there is no setting GPIO 19 high or low required here, if it is enabled you’re going to get the LED on.

To set GPIO 19 as an output:

To disable the output of the pin:

Now I thinkthis works for the onboard LED because of the way it is wired to the 3.3V supply. In fact, for Metal GPIO pin 19, if you try to write a 1 to it you actually turn off the onboard LED and turn on the header pin 3. Speaking of the header pins…

Arduino Header and Pins

Going back to the board schematic, this time on sheet 3 in sections A5, A6, B5, B6, and C5, C6.

Now this is interesting! Our Arduino headers as well have notes on which GPIOs are digital-only (high or low), those that are PWM-capable, and which pins are shared by SPI, I2C, and UART. All we need to do is put this into a nice table, and the following is (I think) a complete GPIO mapping for the SiFive HiFive1 Rev B board.

For example, if you wanted to start your project with blinking an LED on a breadboard, you might start with one of the “standard” digital input/output pins on the header, say pin 7. The chart above (which is derived from the schematic) shows that pin 7 on the header is tied to pin 23 of the GPIO controller. So to use header pin 7 we might write:

Or, we could set at the top of our file something along the lines of #define PIN7 23. Just a thought.

Notice once again that this mapping table shows that there are:

  • 20 digital pins
  • 6 PWM-capable pins
  • 1 SPI
  • 1 I2C
  • 1 UART

Unfortunately SiFive’s HiFive1 Rev B page indicates there are only 19 digital pins and there are 9 PWM-capable ones, so there’s something I’m missing. I think at least for PWM, header pins 17, 18, and 19 on the 6-pin header (to the left of the ESP32) are PWM-capable, though that isn’t clear from the schematic. I’ve asked about that here on the SiFive Forums and will reconcile this post once I learn more.

Getting Some Code

This code is a work in progress and is modeled around the Arduino digital IO library. In digitalio.c you’ll see my take on the functions pinMode and digitalWrite. There is also a delay function to write the ever-popular blinking lights demo. All of this code is MIT licensed with portions copied from the SiFive Freedom E SDK.

Let’s look at how we might use these functions to put the onboard LED through all of the possible colors.

main.c:

Recall the GPIO pins that map to the on-board LEDs are:

  • Red – GPIO_22
  • Green – GPIO_19
  • Blue – GPIO_21

We iterate from 0 to 7 in a loop, test the bits, and set the pins as outputs (since we’re using the onboard LEDs) or disable them. The result is a nice rainbow light show from the HiFive1. If you connect to the serial port you’ll also see the colors being printed out as they are cycled through:

Lagniappe

The code that’s actually uploaded to GitHub includes stepping through the binary representation of our LED rainbow and displaying that if you hook up a few LEDs to your breadboard. Check out the code and look closely here at header pins 2, 4, and 7.

Closing Thoughts and What’s Next

Nothing is more fun than working with microcontrollers and embedded systems, and the HiFive1 is no exception. If you take a look at gpios.h in GitHub you can see that I’m looking as to how to best add additional #defines for the various pins. We will see.

By

An Introduction to the HiFive1 Rev B and RISC-V

Today I’d like to introduce you to a new development board, the HiFive1 Rev B. Equipped with a RISC-V Freedom E310 microcontroller and designed with an Arduino Uno “form factor”, the HiFive1 Rev B is a neat little board that I hope to learn and develop for.

My HiFive1

There is a lot of material out there about RISC-V and how it is going to change the future of CPUs, but what attracted me to it was the notion of a completely open standard Instruction Set Architecture (ISA). That and I think working with new hardware and development environments is cool.

Getting Started

The Getting Started Guide is crucial to read. If you’re anything like me you want to dig in as quickly as possible with as little reading as possible, but trust me, reading the guide first is very useful.

You don’t get anything but the HiFive1 Rev B board if you’ve ordered it from Crowd Supply and will need a trusty USB-A male to USB-micro-B male cable. This connection can be used for both serial communication and power. Of course, if you have only a system with USB-C you’ll need some set of adapters to get to USB micro-B.

For the host platform we will be using a MacBook Pro (Retina, 13-inch, Early 2015) running macOS 10.15 (Catalina). Hopefully if you’re reading this with the intention of working on the HiFive1 with your Macbook Pro you’ll already have the best terminal program ever installed, but if you don’t regular Terminal.app works.

Let’s see our boot screen first:

To see this boot screen you’ll need to use a serial terminal program. macOS is going to present the HiFive as the two USB modem devices in the /dev directory.

The first cu.usbmodem device presented will be the HiFive1, and my suggestion is to open an iTerm and use screen to connect to it. 115200 bps is your speed and the default 8N1 settings should work, so in our case screen /dev/cu.usbmodem0009790151821 115200 is all we had to type in the terminal.

Time to Develop

There are several key pieces of software you’ll need to install on your Mac to begin developing on the HiFive1.

  • a toolchain (i.e., the compiler, assembler, linker, and associated libraries)
  • OpenOCD On-Chip Debugger
  • the Freedom E SDK
  • Segger J-Link OB debugger

We’ll take each in turn.

Installing the Toolchain and OpenOCD

The reference toolchain is a GNU Embedded Toolchain — v2019.08.0 and can be downloaded directly from SiFive. Go to the Boards page, scroll down until you see the section labeled Prebuilt RISC-V GCC Toolchain and Emulator.

Download both the GNU toolchain and OpenOCD packages and untar both into a suitable installation location. I prefer to keep things like this in the /opt directory, so we’ll do the same here in /opt/riscv.

Before going any further ensure that the compiler can run:

You may have received the error message "riscv64-unknown-elf-gcc" cannot be opened because the developer cannot be verified.. Now, this may be controversial, but I don’t hold to my OS telling me what software I can and can’t run, so let’s get rid of that silliness with spctl:

Let’s try again:

Much better.

Get the SDK

We have a HiFive1 board which uses the Freedom E310 chip, thus will want to get the Freedom E SDK. For this I like to keep the SDK in my projects directory.

Note: You must use --recursive here to check out all of the required packages.

Now, let’s compile that first program!

In the top-level directory freedom-e-sdk is a set of Makefiles that make it easy to compile and generate an image suitable for uploading to the HiFive1 board. In this case, PROGRAM is the name of a subdirectory in freedom-e-sdk/software and TARGET is the board you have.

If this is the first time through you’re going to see a bunch of gibbersh about Python, pip3, virtualenv, etc:

And, if you receive an error regarding the C compiler cannot create executables, you need to set your RISCV_PATH environment variable to point to the correct toolchain like export RISCV_PATH=/opt/riscv/riscv64-unknown-elf-gcc-8.3.0-2019.08.0-x86_64-apple-darwin'.

It’s often a good idea to put the various environment variables in a file such as sifive.env and this source the script into your environment.

sifive.env:

If everything worked properly you’ll see at the end something like after compiling.

Installing J-Link

Now, we’re going to upload this to our board, but we will need the Segger J-Link OB debugger. If it isn’t installed you’ll see something like this when trying to use the upload target.

To get J-Link head over to the download page and grab the J-Link Software and Documentation pack for macOS.

Install per the instructions, and once that is done you can go back to your SDK directory and type:

If everything is installed correctly and the board is attached you’ll see something like:

And that’s it! If you have a terminal window with a connection to the serial output of the board you’ll see Hello, World!.

Your Own C Program

In the directory freedom-e-sdk there is a software folder that has an example template. We’ll use that to create our own ASCII art banner.

Copy the template with something like cp -R software/empty software/leo-welcome and then edit the software/leo-welcome/Makefile to change the PROGRAM name to leo-welcome. Open main.c in the same directory and replace the contents with:

Compile and upload with make PROGRAM=leo-welcome TARGET=sifive-hifive1-revb upload and behold.

Some Assembly

I’ll be honest, I struggled with this part, but that’s primarily due to the school of hard knocks with piecing together the calling convention for RISC-V. Let’s review a few examples.

Hello World in RISC-V Assembly

Again, start off with the example folder inside freedom-e-sdk with something like

In this case we’re going to write Hello World in assembly so delete software/helloasm/main.c and instead create a file called main.S with the following content.

main.S:

In RISC-V the a-registers will contain our procedure arguments, the procedure here being C printf. We use la (load address) to bring the address of the hellomsg label into a0 and then call the printf function. All of these, in reality, are pseudoinstructions.

The Makefile in the template will pick up files with a .S extension, so make PROGRAM=helloasm upload will assemble, link, and upload our file to the HiFive1.

Counting Down

Finally, let’s look at a countdown routine with a max and min. Here things are a bit more complicated as we are going to make use of a prologue and epilogue in our routine. The prologue saves the return address on the stack, and the epilogue loads the address back into the ra register such that the instruction ret will branch back to our caller.

countdown.S:

We can call this function with C like this:

main.c:

Compile and upload!

Good References

There are a lot of great references on RISC-V, its instruction set architecture, and so on. I’ve compiled a few of my favorites here.

Closing Thoughts and What’s Next

That wraps it up for this first look at the SiFive HiFive1 Rev B board. Of course, we haven’t even talked about the ESP32-based wireless capabilities of the board, haven’t talked about the Freedom Metal library or any of the stuff that will accelerate our development. Perhaps that’s next!

And, if you’ve made it this far, you might want to check out our next post on exploring the HiFive1 GPIO pins.