↓ Skip to main content
  1. Blog/
  2. nRF52840 Web Server/

Integrating FatFs and W5500 with the Shared SPI Bus

Preface
#

In the previous article, I built a read-only SD card driver that allows the nRF52840 to read raw blocks of data from an SD card. However, the driver does not understand files or directories.

Now, let’s integrate the FatFs file system to allow the nRF52840 to access files stored on the SD card. I will also set up communication with the W5500 Ethernet controller using the WIZnet ioLibrary and the shared SPI driver.

With these integrations, the firmware will have file-level access to the SD card and a way to communicate with the Ethernet controller.

GitHub Repo: https://github.com/codetit4n/nrf52840-webserver

Design Goals
#

  • Read-only file access: Integrate FatFs with the SD card driver to allow files and directories to be accessed from the SD card.
  • W5500 communication: Integrate WIZnet ioLibrary with the shared SPI driver to communicate with the W5500 Ethernet controller.
  • Reuse existing drivers: Use the SPI and SD card drivers built previously.
  • Minimal configuration: Configure both libraries to use only the features required by the web server.

Architecture
#

The diagram below illustrates how FatFs and WIZnet ioLibrary are connected to the existing drivers. FatFs provides file system access through its disk I/O layer, which connects to the SD card driver. Similarly, WIZnet ioLibrary communicates with the W5500 Ethernet controller through the W5500 port layer. Both use the same shared SPI driver to communicate with their respective devices.

FatFs and WIZnet ioLibrary integration architecture using the shared SPI driver
FatFs and WIZnet ioLibrary integration architecture

NOTE: In this article, I will focus on connecting FatFs and WIZnet ioLibrary to the existing drivers.

Setting Up File Storage with FatFs
#

Relevant Source Code
#

NOTE: I downloaded FatFs from its website and added the source files to third_party/FatFs/. The library is used as-is, except for the configuration and disk I/O files, which were modified for the project.

Configuring FatFs
#

FatFs provides several configuration options through its ffconf.h file, allowing us to enable or disable features depending on the application’s requirements.

For this project, I made only a few changes to the default configuration:

-#define FF_FS_READONLY 0
+#define FF_FS_READONLY 1

-#define FF_USE_LFN 0
-#define FF_MAX_LFN 255
+#define FF_USE_LFN 1
+#define FF_MAX_LFN 64
  • FF_FS_READONLY = 1: Enables read-only mode, removing file-writing functions that are unnecessary for the web server.
  • FF_USE_LFN = 1: Enables long filename support, allowing files with names longer than the traditional FAT 8.3 format. This is useful for the web server, where files are accessed using their names in the requested URL.
  • FF_MAX_LFN = 64: Limits the long filename working buffer to 64 UTF-16 code units instead of the default 255, reducing memory usage while still supporting filenames of sufficient length for the static files.

All other configuration options are left at their default values.

Connecting FatFs to the SD Driver
#

Now that FatFs is configured, let’s connect it to the SD card driver. FatFs handles files and directories, but it does not communicate with the SD card directly. Instead, it uses a disk I/O interface defined in diskio.h, implemented in diskio.c.

The following functions are part of this interface:

FunctionPurpose
disk_status()Returns the current status of the storage device.
disk_initialize()Reports whether the storage device is initialized.
disk_read()Reads one or more sectors from the storage device.
disk_write()Writes sectors to the storage device.
disk_ioctl()Handles additional control requests, such as retrieving the sector count.

Since the project uses only one SD card, I configured FatFs to support a single logical volume and use physical drive number 0 throughout the disk I/O implementation.

Disk Status and Initialization

The disk_status() and disk_initialize() functions are quite simple in the implementation. Both check whether the SD card has already been initialized using sd_is_initialized().

if (pdrv != 0) {
    return STA_NOINIT;
}

return sd_is_initialized() ? 0 : STA_NOINIT;

Notice that disk_initialize() does not call sd_init(). This is because the SD card is already initialized during application startup. The function simply reports its current initialization status to FatFs.

Reading Sectors

The most important function is disk_read(). FatFs can request multiple sectors in a single call, whereas the sd_read_block() function, implemented in the previous article, reads only one 512-byte block at a time.

To handle this, disk_read() reads the requested sectors one at a time:

DRESULT disk_read(BYTE pdrv, BYTE* buff, LBA_t sector, UINT count) {
    // ... validate arguments and SD card initialization

    uint64_t block_count = sd_get_block_count();
    // ... validate the requested sector range

    // read the requested sectors one block at a time
    for (UINT i = 0; i < count; i++) {
        uint32_t block = (uint32_t)(sector + i);
        BYTE* destination = buff + ((size_t)i * SD_BLOCK_LEN);

        if (sd_read_block(block, destination) != SD_OK) {
            return RES_ERROR;
        }
    }

    return RES_OK;
}

For each iteration, the block number is incremented, and the destination pointer is advanced by SD_BLOCK_LEN (512 bytes). This allows the requested sectors to be stored consecutively in the buffer provided by FatFs.

If any block read fails, the function returns RES_ERROR. Otherwise, it returns RES_OK after all requested sectors have been read.

Disk Control Operations

FatFs also uses disk_ioctl() to request information about the underlying storage device.

My implementation handles the following commands:

DRESULT disk_ioctl(BYTE pdrv, BYTE cmd, void* buff) {
    // ... validate the physical drive and SD card initialization

    switch (cmd) {
    case CTRL_SYNC:
        return RES_OK; // read-only storage

    case GET_SECTOR_COUNT:
        // ... validate the buffer
        *(LBA_t*)buff = (LBA_t)sd_get_block_count();
        return RES_OK;

    case GET_SECTOR_SIZE:
        // ... validate the buffer
        *(WORD*)buff = SD_BLOCK_LEN;
        return RES_OK;

    case GET_BLOCK_SIZE:
        // ... validate the buffer
        *(DWORD*)buff = 1;
        return RES_OK;

    default:
        return RES_PARERR;
    }
}
  • CTRL_SYNC: Returns RES_OK since the storage is read-only and there are no pending writes to synchronize.
  • GET_SECTOR_COUNT: Returns the total number of sectors using sd_get_block_count(). The block count is calculated during SD card initialization by reading the card’s CSD register.
  • GET_SECTOR_SIZE: Returns SD_BLOCK_LEN (512 bytes), matching the sector size supported by the SD card driver.
  • GET_BLOCK_SIZE: Returns 1 as the reported erase block size in sectors. This is not a measurement of the SD card’s actual erase block size.

Finally, disk_write() simply returns RES_WRPRT, indicating that the storage device is write-protected. Since FatFs is configured in read-only mode, file-writing operations are disabled.

DRESULT disk_write(
    BYTE pdrv, /* Physical drive nmuber to identify the drive */
	const BYTE* buff,     /* Data to be written */
	LBA_t sector,	      /* Start sector in LBA */
	UINT count	      /* Number of sectors to write */
) {

	(void)pdrv;
	(void)buff;
	(void)sector;
	(void)count;

	return RES_WRPRT;
}

With the disk I/O interface implemented, FatFs can now use the SD card driver to access the underlying storage without needing to know how SPI communication or SD commands are handled.

Mounting and Reading Files
#

With the disk I/O interface implemented, I can now mount the filesystem and access files stored on the SD card using FatFs.

Mounting the Filesystem

During application startup, the startup_task() initializes the SD card using sd_init(). Once initialization succeeds, I can mount the filesystem using f_mount().

The relevant part of the implementation in main.c looks like this:

static FATFS fs;

// ... inside startup_task()

status = sd_init();

// ... handle initialization failures and retries

if (status == SD_OK) {
    FRESULT fr = f_mount(&fs, "0:", 1);

    if (fr != FR_OK) {
        sd_set_available(0);
        // ... log mount failure
    } else {
        sd_set_available(1);
        // ... log mount success
    }
}

Here, fs is a FATFS object representing the filesystem, "0:" identifies the logical volume, and the final argument 1 tells FatFs to mount the volume immediately rather than delaying the operation until the first file access.

If mounting succeeds, set sd_set_available(1) to indicate that the storage is ready for use. Otherwise, it is marked unavailable (sd_set_available(0)).

Reading Files

Once the filesystem is mounted, I can use FatFs functions such as f_open(), f_read(), and f_close() to read files from the SD card.

For example, a file stored at 0:/static/HELLO.TXT can be opened and read as follows (simplified example):

FIL file;
UINT bytes_read;
uint8_t buffer[128];

FRESULT fr = f_open(&file, "0:/static/HELLO.TXT", FA_READ);

if (fr == FR_OK) {
    fr = f_read(&file, buffer, sizeof(buffer), &bytes_read);

    // ... process the data if the read succeeds

    f_close(&file);
}

The FA_READ flag opens the file for reading, while f_read() copies up to the requested number of bytes into the provided buffer. The bytes_read variable tells us how many bytes were actually received.

FatFs handles locating the file and translating file-level reads into sector reads through the disk_read() implementation.

With this, the storage setup is complete. I can now access files on the SD card without manually handling sectors or FAT filesystem structures.

Setting Up the W5500 Ethernet Controller
#

Relevant Source Code
#

NOTE: WIZnet ioLibrary is included as a Git submodule, pinned to a specific commit.

Connecting WIZnet ioLibrary to the SPI Driver
#

Unlike FatFs, which uses a disk I/O interface to access the SD card driver, WIZnet ioLibrary uses callback functions to communicate with the W5500.

Some functions are needed to be registered with ioLibrary to handle SPI transfers, chip-select operations, and critical-section management. The following table summarizes the callbacks required by ioLibrary:

FunctionPurpose
reg_wizchip_cris_cbfunc()Registers callbacks for entering and exiting critical sections.
reg_wizchip_cs_cbfunc()Registers callbacks for selecting and deselecting the W5500 using its CS pin.
reg_wizchip_spi_cbfunc()Registers callbacks for single-byte SPI reads and writes.
reg_wizchip_spiburst_cbfunc()Registers callbacks for transferring multiple bytes over SPI.

These callbacks are implemented in the W5500 port layer, allowing ioLibrary to communicate with the W5500 through the shared SPI driver without needing to know how the nRF52840’s SPIM peripheral is configured.

The callbacks are registered during W5500 initialization:

reg_wizchip_cs_cbfunc(cs_select, cs_deselect);
reg_wizchip_spi_cbfunc(w5500_spi_readbyte, w5500_spi_writebyte);
reg_wizchip_spiburst_cbfunc(w5500_spi_readburst, w5500_spi_writeburst);
reg_wizchip_cris_cbfunc(w5500_cris_enter, w5500_cris_exit);

SPI and Chip-Select Callbacks

The W5500 device configuration uses SPI mode 0, a 16 MHz clock, MSB-first transfers, and the W5500’s dedicated chip-select pin.

static const spi_device_t w5500_dev = {
    .cs_pin = W5500_CSN_PIN, // defined in board.h
	.mode = SPI_MODE_0, // CPOL = 0, CPHA = 0
	.frequency = SPI_FREQ_16M, // 16 MHz
	.order = SPI_MSB_FIRST,
	.dummy_byte = 0xFF // W5500 ignores dummy bytes, any value can be used
};

The CS callbacks use spi_begin() and spi_end() to start and end transactions on the shared SPI bus:

void cs_select(void) {
    spi_begin(&w5500_dev);
}

void cs_deselect(void) {
    spi_end();
}

Similarly, the SPI callbacks use spi_rx() and spi_tx() to receive and transmit data:

uint8_t w5500_spi_readbyte(void) {
    uint8_t b;
    (void)spi_rx(&b, 1);
    return b;
}

void w5500_spi_writebyte(uint8_t wb) {
    (void)spi_tx(&wb, 1);
}

void w5500_spi_readburst(uint8_t* pBuf, uint16_t len) {
    (void)spi_rx(pBuf, len);
}

void w5500_spi_writeburst(uint8_t* pBuf, uint16_t len) {
    (void)spi_tx(pBuf, len);
}

NOTE: The readbyte and writebyte callbacks transfer a single byte, while readburst and writeburst transfer multiple bytes in a single call. All four functions use the same SPI driver, with the transfer length determining how much data is received or transmitted.

These functions act as wrappers around the shared SPI driver, allowing ioLibrary to perform SPI transactions without directly accessing the nRF52840’s SPIM registers.

Critical-Section Callbacks

The critical-section callbacks use a FreeRTOS mutex to coordinate access to ioLibrary operations:

void w5500_cris_enter(void) {
    xSemaphoreTake(w5500_mutex, portMAX_DELAY);
}

void w5500_cris_exit(void) {
    xSemaphoreGive(w5500_mutex);
}

NOTE: The w5500_cris_enter() callback acquires the mutex, while w5500_cris_exit() releases it.

This mutex is separate from the mutex used by the shared SPI driver. The ioLibrary mutex protects W5500 operations that require serialization, while the shared SPI mutex prevents the W5500 and SD card from using the SPI bus simultaneously.

Initializing the W5500
#

With the callbacks implemented, I can now initialize the W5500 Ethernet controller using w5500_init().

The initialization function performs the following steps:

  1. Create a FreeRTOS mutex for the ioLibrary critical-section callbacks.
  2. Initialize the W5500 as an SPI device using the shared SPI driver.
  3. Register the chip-select, SPI transfer, and critical-section callbacks with ioLibrary.
  4. Perform a hardware reset of the W5500.
  5. Configure the W5500’s socket TX and RX buffers.

The relevant implementation is shown below:

int8_t w5500_init(void) {
    w5500_mutex = xSemaphoreCreateMutexStatic(&w5500_mutex_buf);
    configASSERT(w5500_mutex);

    spi_device_init(&w5500_dev);

    // ... register ioLibrary callbacks

    // ... configure W5500_RST_PIN as an output

    pin_low(W5500_RST_PIN);
    vTaskDelay(pdMS_TO_TICKS(10));
    pin_high(W5500_RST_PIN);

    // Let W5500 finish power-up before first access
    vTaskDelay(pdMS_TO_TICKS(200));

    uint8_t txsize[8] = {2, 2, 2, 2, 2, 2, 2, 2};
    uint8_t rxsize[8] = {2, 2, 2, 2, 2, 2, 2, 2};

    return wizchip_init(txsize, rxsize);
}

Hardware Reset

The W5500 has an active-LOW reset pin, which is connected to a GPIO pin on the nRF52840.

During initialization, we configure this GPIO as an output and pull it LOW for 10 ms to reset the controller. The pin is then driven HIGH to release the reset, followed by a 200 ms delay before accessing the W5500.

NOTE: The hardware reset is not strictly necessary, as the W5500 can be initialized without it. However, it ensures that the controller starts in a known state.

Socket Memory Configuration

The W5500 supports eight hardware sockets and provides 16 KiB of TX memory and 16 KiB of RX memory.

In my implementation, I allocate 2 KiB of TX and 2 KiB of RX memory to each socket, using the wizchip_init() function provided by ioLibrary.

This distributes the available memory equally across all eight sockets:

  • TX memory: 8 × 2 KiB = 16 KiB
  • RX memory: 8 × 2 KiB = 16 KiB
Datasheet ReferenceW5500 memory organization diagram from the datasheet

Finally, wizchip_init() configures the socket buffer allocation and returns a status indicating whether initialization succeeded.

With this, the W5500 is initialized and ready for further network configuration.

Conclusion
#

With FatFs integrated, I can now access files stored on the SD card without manually reading individual sectors. I have also connected WIZnet ioLibrary to the shared SPI driver and initialized the W5500 Ethernet controller.