Skip to content

Instantly share code, notes, and snippets.

@DominicMaas
Last active October 15, 2023 14:28
Show Gist options
  • Save DominicMaas/4bc8f6625cba2ba1a0c722792d87fdad to your computer and use it in GitHub Desktop.
Save DominicMaas/4bc8f6625cba2ba1a0c722792d87fdad to your computer and use it in GitHub Desktop.
Not much testing, but this should work for using LittleFS with the Raspberry Pi Pico built in flash chip.
#pragma once
#include "pico/stdlib.h"
#include "pico/binary_info.h"
#include "hardware/flash.h"
#include "hardware/sync.h"
#include <lfs.h>
// Define the flash sizes
// This is setup to read a block of the flash from the end
#define BLOCK_SIZE_BYTES (FLASH_SECTOR_SIZE)
#define HW_FLASH_STORAGE_BYTES (1408 * 1024)
#define HW_FLASH_STORAGE_BASE (PICO_FLASH_SIZE_BYTES - HW_FLASH_STORAGE_BYTES) // 655360
int pico_read(const struct lfs_config *c, lfs_block_t block, lfs_off_t off, void *buffer, lfs_size_t size)
{
uint32_t fs_start = XIP_BASE + HW_FLASH_STORAGE_BASE;
uint32_t addr = fs_start + (block * c->block_size) + off;
// printf("[FS] READ: %p, %d\n", addr, size);
memcpy(buffer, (unsigned char *)addr, size);
return 0;
}
int pico_prog(const struct lfs_config *c, lfs_block_t block, lfs_off_t off, const void *buffer, lfs_size_t size)
{
uint32_t fs_start = HW_FLASH_STORAGE_BASE;
uint32_t addr = fs_start + (block * c->block_size) + off;
// printf("[FS] WRITE: %p, %d\n", addr, size);
uint32_t ints = save_and_disable_interrupts();
flash_range_program(addr, (const uint8_t *)buffer, size);
restore_interrupts(ints);
return 0;
}
int pico_erase(const struct lfs_config *c, lfs_block_t block)
{
uint32_t fs_start = HW_FLASH_STORAGE_BASE;
uint32_t offset = fs_start + (block * c->block_size);
// printf("[FS] ERASE: %p, %d\n", offset, block);
uint32_t ints = save_and_disable_interrupts();
flash_range_erase(offset, c->block_size);
restore_interrupts(ints);
return 0;
}
int pico_sync(const struct lfs_config *c)
{
return 0;
}
// configuration of the filesystem is provided by this struct
const struct lfs_config PICO_FLASH_CFG = {
// block device operations
.read = &pico_read,
.prog = &pico_prog,
.erase = &pico_erase,
.sync = &pico_sync,
// block device configuration
.read_size = FLASH_PAGE_SIZE, // 256
.prog_size = FLASH_PAGE_SIZE, // 256
.block_size = BLOCK_SIZE_BYTES, // 4096
.block_count = HW_FLASH_STORAGE_BYTES / BLOCK_SIZE_BYTES, // 352
.block_cycles = 16, // ?
.cache_size = FLASH_PAGE_SIZE, // 256
.lookahead_size = FLASH_PAGE_SIZE, // 256
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment