Code Portal

外付けEEPROMをファイルシステムとして使う

Ver 0.0.0 最終更新日: 2026-09-27 C++

はてなブログの解説記事に対応するソースコードです。コピペの手間を省く即実行ファイルや完全版はcodocエリアから取得できます。

ソースコード

※表示用プレビューです。一括ファイルはページ下部より取得できます。 ソースの説明は本家ブログの方でどうぞ。

📄 main.cpp
#include <stdio.h>
#include <string.h>
#include "pico/stdlib.h"
#include "hardware/i2c.h"
#include "hardware/pio.h"
#include "pico/cyw43_arch.h"
#include "hardware/uart.h"
#include "lib/i2cif.hpp"
#include "lib/fatfs/diskio.h"
#include "lib/eeprom/24fc512.hpp"
#include "lib/eeprom/24fc512.h"
#include "lib/filesystem.hpp"

// I2C Pin Assignment
#define I2C_UNIT i2c1
#define PIN_SDA 10
#define PIN_SCL 11

I2CIF *i2cif;

// 異常発生時警告点滅(継続できないとき)
void error_blink(void) {
    bool led_on = true;
    // EEPROM_dump(0, 512);
    while (true) {
        cyw43_arch_gpio_put(CYW43_WL_GPIO_LED_PIN, led_on ? 1 : 0);
        led_on = !led_on;
        sleep_ms(150);
    }
}

extern "C" int main()
{
    stdio_init_all();

    printf("\n\n");
    printf("=========================\n");
    printf("  EEPROM FS\n");
    printf("          Version 0.0.0\n");
    printf("=========================\n\n");

    // Initialise the Wi-Fi chip
    if (cyw43_arch_init()) {
        printf("Wi-Fi init failed\n");
        return -1;
    }

    i2cif = new I2CIF(I2C_UNIT, PIN_SDA, PIN_SCL);

    // Initialize File System
    init_filesystem(i2cif);

    test_filesystem();

    // メインループ
    bool tft_on = true;
    while (true) {
        cyw43_arch_gpio_put(CYW43_WL_GPIO_LED_PIN, tft_on ? 1 : 0);
        tft_on = !tft_on;
        sleep_ms(1000);
    }
}
📄 lib/i2cif.hpp
// i2cif.hpp - I2C I/F driver

#ifndef __I2CIF_HPP__
#define __I2CIF_HPP__

#include "hardware/i2c.h"
#include "hardware/gpio.h"

class I2CIF {
public:
    i2c_inst_t *i2c;

private:
    uint8_t sda;
    uint8_t scl;
    uint baud = 400000; // Default 400KHz

private:
    void write_word(uint8_t adrs, uint8_t *data, int len, bool cont);
    void read_word(uint8_t adrs, uint8_t *data, int len, bool cont);

public:
    I2CIF(i2c_inst_t *i2c, uint8_t sda, uint8_t scl, uint baud = 400000);

    void set_baud(uint baud);

    void write_cmd(uint8_t adrs, uint8_t cmd);
    void write_data(uint8_t adrs, uint8_t *data, size_t length);
    void read_data(uint8_t adrs, uint8_t *data, size_t length);
};

#endif  // __I2CIF_HPP__
📄 lib/i2cif.cpp
// i2cif.cpp - I2C I/F driver module

#include <stdlib.h>
#include <cstring>
#include "i2cif.hpp"

void I2CIF::write_word(uint8_t adrs, uint8_t *data, int len, bool cont = false)
{
    i2c_write_blocking(this->i2c, adrs, data, len, cont);
}

void I2CIF::read_word(uint8_t adrs, uint8_t *data, int len, bool cont = false)
{
    i2c_read_blocking(this->i2c, adrs, data, len, cont);
}

I2CIF::I2CIF(i2c_inst_t *i2c, uint8_t sda, uint8_t scl, uint baud) : i2c(i2c), sda(sda), scl(scl), baud(baud)
{
    gpio_set_function(this->sda, GPIO_FUNC_I2C);
    gpio_pull_up(this->sda);

    gpio_set_function(this->scl, GPIO_FUNC_I2C);
    gpio_pull_up(this->scl);

    i2c_init(this->i2c, this->baud);
}

void I2CIF::set_baud(uint baud)
{
    this->baud = baud;
    i2c_set_baudrate(this->i2c, baud);
}

void I2CIF::write_cmd(uint8_t adrs, uint8_t cmd)
{
    uint8_t buf[2];

    buf[0] = 0x80;  // Co = 1, D/C# = 0
    buf[1] = cmd;
    this->write_word(adrs, buf, 2);
}

void I2CIF::write_data(uint8_t adrs, uint8_t* data, size_t length)
{

    uint8_t *buf = (uint8_t *)malloc(length + 1);
    buf[0] = 0x40;  // Co = 0, D/C# = 1
    memcpy(buf + 1, data, length);
    this->write_word(adrs, buf, (uint)length + 1);
    free(buf);
}

void I2CIF::read_data(uint8_t adrs, uint8_t *data, size_t length)
{
    this->read_word(adrs, data, length);
}
📄 lib/eeprom/24fc512.hpp
// 24fc512.hpp - I2C 512Kbit EEPROM

#ifndef __24FC512_HPP__
#define __24FC512_HPP__

#include "lib/i2cif.hpp"

class BufCtrl {
private:
    I2CIF *i2cif;
    int bufptr = 0;
    uint8_t i2c_adrs;

public:
    uint8_t *buffer;

public:
    BufCtrl(I2CIF *i2cif, uint8_t i2c_adrs);
    ~BufCtrl();

    void begin_transmission(void);
    int  end_transmission(bool nostop);
    int read(uint8_t *data, int datalen, bool nostop);
    void write(uint8_t data);
    void write(uint8_t *data, size_t datalen);
};


class EEPROM {
private:
    I2CIF *i2cif;
    BufCtrl *bufctrl;
    uint8_t i2c_adrs;

public:
    EEPROM(I2CIF *i2cif, uint8_t i2c_adrs);
    ~EEPROM();

    size_t get_block_size(void);

    uint8_t read_byte(uint adrs);
    uint8_t *read_bytes(uint adrs, uint8_t *buf, uint bytes);
    uint8_t *read_page(uint adrs, uint8_t *buf);

    bool write_byte(uint adrs, uint8_t data);
    bool write_bytes(uint adrs, uint8_t *data, uint bytes);
    bool write_page(uint adrs, uint8_t *data);
};


#endif  // __24FC512_HPP__
📄 lib/eeprom/24fc512.cpp
// 24FC512 - I2C 512Kbit EEPROM

#include "stdlib.h"
#include <stdio.h>
#include "string.h"
#include "24fc512.hpp"

#define PAGE_BUF_SIZE 128
#define MAX_PAGE_BUF_SIZE (PAGE_BUF_SIZE + 2)

/*
 * C Wrapper
 */

extern "C" {

    uint8_t *EEPROM_read_page(void *obj_ptr, uint adrs, uint8_t *buf)
    {
        if (obj_ptr) {
            return static_cast<EEPROM *>(obj_ptr)->read_page(adrs, buf);
        }
        return NULL;
    }

    bool EEPROM_write_page(void *obj_ptr, uint adrs, uint8_t *data)
    {
        if (obj_ptr) {
            return static_cast<EEPROM *>(obj_ptr)->write_page(adrs, data);
        }
        return false;
    }

    uint8_t *EEPROM_read_sector(void *obj_ptr, uint sector, uint8_t *buf, int block_size = 4)
    {
        if (!obj_ptr) return NULL;
        uint adrs = sector * 128 * block_size;

        for (int i=0; i<block_size; i++) {
            if (!EEPROM_read_page(obj_ptr, adrs, buf)) return NULL;
            adrs += 128;
            buf += 128;
        }
        return buf;
    }

    bool EEPROM_write_sector(void *obj_ptr, uint sector, uint8_t *data, int block_size = 4)
    {
        bool stat = false;

        if (!obj_ptr) return false;
        uint adrs = sector * 128 * block_size;

        for(int i=0; i<block_size; i++) {
            stat = EEPROM_write_page(obj_ptr, adrs, data);
            if (!stat) break;
            adrs += 128;
            data += 128;
        }
        return stat;
    }

// FAT12/FAT16の定義
struct __attribute__((packed))FAT_BPB {

    uint8_t BS_JmpBoot[3];      // ブートストラップコードへのジャンプ命令(x86命令)
    uint8_t BS_OEMName[8];      // "MSWIN4.1"
    uint16_t BPB_BytsPerSec;    // バイト単位のセクタサイズ
    uint8_t BPB_SecPerClus;     // アロケーションユニット当たりのセクタ数
    uint16_t BPB_RsvdSecCnt;    // 予約領域のセクタ数(0以外)
    uint8_t BPB_NumFATs;        // FATの数(2に設定のこと)
    uint16_t BPB_RootEntCnt;    // ルートディレクトリに含まれるディレクトリエントリの数を示す
    uint16_t BPB_TotSec16;      // ボリュームの総セクタ数
    uint8_t BPB_Media;          // 0xF0が標準値
    uint16_t BPB_FATSz16;       // 1このFATが占めるセクタ数
    uint16_t BPB_SecPerTrk;     // トラックあたりのセクタ数(特に使用されない)
    uint16_t BPB_NumHeads;      // ヘッド数(特に意味はない)
    uint32_t BPB_HiddSec;       // このボリュームの手前に存在する隠れた物理セクタの数
    uint32_t BPB_TotSec32;      // ボリュームの総セクタ数(総セクタ数が0x10000未満のとき、このフィールドは無効値(0))

    // FAT12/FAT16固有のテーブル
    uint8_t  BS_DrvNum;         // IBM PCのディスクBIOSで使われるドライブ番号
    uint8_t  BS_Reserved;       // 予約(WindwosNTで使用)
    uint8_t  BS_BootSig;        // 拡張ブートシグネチャ
    uint32_t BS_VolID;          // ボリュームシリアル番号
    uint8_t  BS_VolLab[11];     // ボリュームラベル
    uint8_t  BS_FilSysType[8];  // "FAT12   " or "FAT16   " or "FAT     "
    uint8_t  BS_BootCode[448];  // ブートストラップコード(未使用=0)
    uint16_t BS_Sign;           // 0xAA55固定。有効なブートセクタであることを示すブートシグネチャ

} default_fat_bpb = {

    .BS_JmpBoot = {0xeb, 0xff, 0x90},
    .BS_OEMName = {'M', 'S', 'W', 'I', 'N', '4', '.', '1'},
    .BPB_BytsPerSec = 512,
    .BPB_SecPerClus = 1,
    .BPB_RsvdSecCnt = 1,
    .BPB_NumFATs = 2,
    .BPB_RootEntCnt = 512,
    .BPB_TotSec16 = 0x10000 / 512,
    .BPB_Media = 0xf0,
    .BPB_FATSz16 = 512,
    .BPB_SecPerTrk = 16,
    .BPB_NumHeads = 16,
    .BPB_HiddSec = 0,
    .BPB_TotSec32 = 0,

    // FAT12/FAT16のテーブル
    .BS_DrvNum = 0x80,
    .BS_Reserved = 0,
    .BS_BootSig = 0x29,
    .BS_VolID =  20260911,
    .BS_VolLab = {'E', 'E', 'P', 'R', 'O', 'M', 0, 0, 0, 0, 0},
    .BS_FilSysType = {'F', 'A', 'T', '1', '2', ' ', ' ', ' '},
    .BS_Sign = 0xaa55,
};


    bool EEPROM_physical_format(void *obj_ptr)
    {
        bool stat;
        uint8_t *buf;
        if (!obj_ptr) return false;

        stat = EEPROM_write_sector(obj_ptr, 0, (uint8_t *)&default_fat_bpb);
        if (!stat) return stat;

        buf = (uint8_t *)calloc(512, 1);
        stat = EEPROM_write_sector(obj_ptr, 1, buf);
        free(buf);

        return stat;
    }
}

/*
 * Class BufCtrl
 */

BufCtrl::BufCtrl(I2CIF *i2cif, uint8_t i2c_adrs) : i2cif(i2cif), i2c_adrs(i2c_adrs), bufptr(0) {
    this->buffer = (uint8_t *)malloc(MAX_PAGE_BUF_SIZE);
}
BufCtrl::~BufCtrl() {
    free(this->buffer);
}

void BufCtrl::begin_transmission(void) {
    this->bufptr = 0;
}
int BufCtrl::end_transmission(bool nostop = false) {
    return i2c_write_blocking(this->i2cif->i2c, this->i2c_adrs, this->buffer, this->bufptr, nostop);
}
int BufCtrl::read(uint8_t *data, int datalen, bool nostop = false) {
    return i2c_read_blocking(this->i2cif->i2c, this->i2c_adrs, data, datalen, nostop);
}
void BufCtrl::write(uint8_t data) {
    if (this->bufptr > MAX_PAGE_BUF_SIZE) return;
    this->buffer[this->bufptr++] = data;
}
void BufCtrl::write(uint8_t *data, size_t datalen) {
    if (this->bufptr > MAX_PAGE_BUF_SIZE) return;
    if (this->bufptr + datalen > MAX_PAGE_BUF_SIZE) return;
    memcpy(&(this->buffer[this->bufptr]), (void *)data, datalen);
    this->bufptr += datalen;
}

/*
 * Class EEPROM
 */

EEPROM::EEPROM(I2CIF *i2cif, uint8_t i2c_adrs) : i2cif(i2cif), i2c_adrs(i2c_adrs)
{
    this->bufctrl = new BufCtrl(i2cif, i2c_adrs);
}

EEPROM::~EEPROM()
{
    delete this->bufctrl;
}

size_t EEPROM::get_block_size(void)
{
    return PAGE_BUF_SIZE;
}

uint8_t EEPROM::read_byte(uint adrs)
{
    int i;
    uint8_t data = 0xff;

    this->bufctrl->begin_transmission();
    this->bufctrl->write(adrs >> 8);
    this->bufctrl->write(adrs & 0xff);
    for (i=0; i<5; i++) {
        if (this->bufctrl->end_transmission(true) == 0) continue;
        if (this->bufctrl->read(&data, 1, false) == 1) {
            return data;
        }
    }
    return 0xff;
}

uint8_t *EEPROM::read_bytes(uint adrs, uint8_t *buf, uint bytes)
{
    int i;
    this->bufctrl->begin_transmission();
    this->bufctrl->write(adrs >> 8);
    this->bufctrl->write(adrs & 0xff);
    for (i=0; i<5; i++) {
        if (this->bufctrl->end_transmission(true) == 0) continue;
        if (this->bufctrl->read(buf, bytes) == bytes) {
            return buf;
        }
    }

    return NULL;
}

uint8_t *EEPROM::read_page(uint adrs, uint8_t *buf)
{
    int i;

    adrs &= 0xff80;

    this->bufctrl->begin_transmission();
    this->bufctrl->write(adrs >> 8);
    this->bufctrl->write(adrs & 0xff);
    for (i=0; i<5; i++) {
        if (this->bufctrl->end_transmission(true) == 0) continue;
        if (this->bufctrl->read(buf, PAGE_BUF_SIZE) == PAGE_BUF_SIZE) {
            return buf;
        }
    }
    return NULL;
}

bool EEPROM::write_byte(uint adrs, uint8_t data)
{
    this->bufctrl->begin_transmission();
    this->bufctrl->write(adrs >> 8);
    this->bufctrl->write(adrs & 0xff);
    this->bufctrl->write(data);
    for (int i=0; i<5; i++) {
        if (this->bufctrl->end_transmission(false) > 0) {
            sleep_ms(5);
            return true;
        }
    }
    return false;
}

bool EEPROM::write_bytes(uint adrs, uint8_t *data, uint bytes)
{
    int i, ret;

    this->bufctrl->begin_transmission();
    this->bufctrl->write(adrs >> 8);
    this->bufctrl->write(adrs & 0xff);
    this->bufctrl->write(data, bytes);
    for (i=0; i<5; i++) {
        ret = this->bufctrl->end_transmission(false);
        if (ret == 2 + bytes) {
            sleep_ms(5);
            return true;
        }
    }
    return false;
}

bool EEPROM::write_page(uint adrs, uint8_t *data)
{
    adrs &= 0xff80;

    return this->write_bytes(adrs, data, PAGE_BUF_SIZE);
}

📄 lib/eeprom/24fc512.h
// 24fc512.h - 512Kbit EEPROM driver

#ifdef __cplusplus
extern "C" {
#endif

uint8_t *EEPROM_read_page(void *obj_ptr, int adrs, uint8_t *buf);
bool EEPROM_write_page(void *obj_ptr, int adrs, uint8_t *data);
uint8_t *EEPROM_read_sector(void *obj_ptr, int sector, uint8_t *buf, int block_size);
bool EEPROM_write_sector(void *obj_ptr, int sector, uint8_t *data, int block_size);
bool EEPROM_physical_format(void *obj_ptr);

#ifdef __cplusplus
}
#endif
📄 lib/fatfs/eeprom_i2c.c
/*------------------------------------------------------------------------*/
/* Raspberry Pi Pico/PicoW: 24FC512 (I2C mode) control module             */
/*------------------------------------------------------------------------*/
/*
/  Copyright (C) 2018, ChaN, all right reserved.
/
/ * This software is a free software and there is NO WARRANTY.
/ * No restriction on use. You can use, modify and redistribute it for
/   personal, non-profit or commercial products UNDER YOUR RESPONSIBILITY.
/ * Redistributions of source code must retain the above copyright notice.
/
/-------------------------------------------------------------------------*/

#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/i2c.h"
#include "diskio.h"

#include "lib/eeprom/24fc512.h"

extern void *eeprom;

/*--------------------------------------------------------------------------

   Module Private Functions

---------------------------------------------------------------------------*/
# include "ff.h"			/* Obtains integer types */
# include "diskio.h"		/* Declarations of disk functions */

static volatile DSTATUS Stat = STA_NOINIT;	/* Physical drive status */

#define MAX_EEPROM_NO 	1
#define EEPROM_START_ADRS 0x50


/*--------------------------------------------------------------------------

   Public Functions

---------------------------------------------------------------------------*/

/*-----------------------------------------------------------------------*/
/* Initialize disk drive                                                 */
/*-----------------------------------------------------------------------*/

DSTATUS eeprom_disk_initialize (
	BYTE drv		/* Physical drive number */
)
{
	if (drv > FF_VOLUMES) return STA_NOINIT;

	Stat &= ~STA_NOINIT;		// Clear the NoInit flag

	return Stat;
}



/*-----------------------------------------------------------------------*/
/* Get disk status                                                       */
/*-----------------------------------------------------------------------*/

DSTATUS eeprom_disk_status (
	BYTE drv		/* Physical drive number */
)
{
	if (drv > FF_VOLUMES) return STA_NOINIT;

	return Stat;	/* Return disk status */
}



/*-----------------------------------------------------------------------*/
/* Read sector(s)                                                        */
/*-----------------------------------------------------------------------*/

DRESULT eeprom_disk_read (
	BYTE drv,		/* Physical drive number */
	BYTE *buff,		/* Pointer to the data buffer to store read data */
	LBA_t sector,	/* Start sector number (LBA) */
	UINT count		/* Number of sectors to read (1..128) */
)
{
	DWORD sect = (DWORD)sector;
	void *stat;

	if ((drv > FF_VOLUMES) || !count) return RES_PARERR;	/* Check parameter */
	if (Stat & STA_NOINIT) return RES_NOTRDY;	/* Check if drive is ready */

	if (count == 1) {	/* Single sector read */
		stat = EEPROM_read_sector(eeprom, sect, buff, 4);
		count = 0;
	} else {				/* Multiple sector read */
		do {
			stat = EEPROM_read_sector(eeprom, sect, buff, 4);
			if (!stat) break;
			buff += 512;
			sect += 1;
		} while (--count);
	}
	if (stat == false) count = 1;

	return count ? RES_ERROR : RES_OK;	/* Return result */
}



/*-----------------------------------------------------------------------*/
/* Write sector(s)                                                       */
/*-----------------------------------------------------------------------*/

DRESULT eeprom_disk_write (
	BYTE drv,			/* Physical drive number (0) */
	BYTE *buff,			/* Ponter to the data to write */
	LBA_t sector,		/* Start sector number (LBA) */
	UINT count			/* Number of sectors to write (1..128) */
)
{
	DWORD sect = (DWORD)sector;
	bool stat;

	if ((drv > FF_VOLUMES) || !count) return RES_PARERR;		/* Check parameter */
	if (Stat & STA_NOINIT) return RES_NOTRDY;	/* Check drive status */
	if (Stat & STA_PROTECT) return RES_WRPRT;	/* Check write protect */

	if (count == 1) {	/* Single sector write */
		stat = EEPROM_write_sector(eeprom, sect, buff, 4);
		if (stat) count = 0;
	} else {				/* Multiple sector write */
		do {
			stat = EEPROM_write_sector(eeprom, sect, buff, 4);
			if (!stat) break;
			buff += 512;
			sect += 1;
		} while (--count);
		if (!stat) count = 1;
	}

	return count ? RES_ERROR : RES_OK;	/* Return result */
}


/*-----------------------------------------------------------------------*/
/* Miscellaneous drive controls other than data read/write               */
/*-----------------------------------------------------------------------*/

DRESULT eeprom_disk_ioctl (
	BYTE drv,		/* Physical drive number (0) */
	BYTE cmd,		/* Control command code */
	void *buff		/* Pointer to the conrtol data */
)
{
	DRESULT res;
	BYTE n, csd[16];
	DWORD st, ed, csize;
	LBA_t *dp;


	if (drv > FF_VOLUMES) return RES_PARERR;					/* Check parameter */
	if (Stat & STA_NOINIT) return RES_NOTRDY;	/* Check if drive is ready */

	res = RES_ERROR;

	switch (cmd) {
	case CTRL_SYNC :		/* Wait for end of internal write process of the drive */
		res = RES_OK;
		break;

	case GET_SECTOR_COUNT :	/* Get drive capacity in unit of sector (DWORD) */
		*((DWORD *)buff) = 0x10000 / 512;
		res = RES_OK;
		break;

	case GET_SECTOR_SIZE:
		*((WORD *)buff) = 512;
		res = RES_OK;
		break;

	case GET_BLOCK_SIZE :	/* Get erase block size in unit of sector (DWORD) */
		*((DWORD *)buff) = 1;
		res = RES_OK;
		break;

	case CTRL_TRIM :	/* Erase a block of sectors (used when _USE_ERASE == 1) */
		dp = (LBA_t *)buff; st = (DWORD)dp[0]; ed = (DWORD)dp[1];	/* Load sector block */
		st *= 512; ed *= 512;

		unsigned bytes = ed - st;

		res = RES_OK;
		break;

	default:
		res = RES_PARERR;
	}

	return res;
}


/*-----------------------------------------------------------------------*/
/* Disk Initialization                                                   */
/*-----------------------------------------------------------------------*/

DRESULT eeprom_disk_init(void)
{
	DRESULT res;

	res = diskio_new((BYTE)DRIVE_TYPE_NAND, READ_WRITE, 512, 0, 
		(DSTATUS (*)(BYTE))eeprom_disk_status, 
		(DSTATUS (*)(BYTE))eeprom_disk_initialize, 
		(DRESULT (*)(BYTE, BYTE*, LBA_t, UINT))eeprom_disk_read, 
		(DRESULT (*)(BYTE, const BYTE*, LBA_t, UINT))eeprom_disk_write, 
		(DRESULT (*)(BYTE, BYTE, void*))eeprom_disk_ioctl
	);
	return res;
}
📄 lib/filesystem.hpp
// filesystem.hpp - Fat File System i/f

#ifndef __FILESYSTEM_HPP__
#define __FILESYSTEM_HPP__

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "fatfs/diskio.h"
#include "fatfs/ff.h"
#include "eeprom/24fc512.h"
#include "eeprom/24fc512.hpp"

// I2C Pin Assignment
#define I2C_UNIT i2c1
#define PIN_SDA 10
#define PIN_SCL 11

extern void error_blink(void);
bool init_filesystem(I2CIF *i2cif);

void EEPROM_dump(uint adrs, uint len);
void test_filesystem(void);

#endif  // __FILESYSTEM_HPP__
📄 lib/filesystem.cpp
// filesystem.cpp - File System Initializer

#include "filesystem.hpp"

EEPROM *eeprom;

FATFS FatFSMmc;
FATFS FatFSEeprom;

bool init_filesystem(I2CIF *i2cif)
{
    DSTATUS stat;
    FRESULT stat_f;

    // EEPROM初期設定

    // I2CIF *i2cif = new I2CIF(I2C_UNIT, PIN_SDA, PIN_SCL);
    eeprom = new EEPROM(i2cif, 0x50);

    // EEPROMの初期化
    stat = eeprom_disk_init();
    if (stat != RES_OK) {
        printf("EEPROM disk init failed width %d.\n", stat);
        error_blink();
    }
    printf("disk init eeprom OK.\n");

    BYTE work[FF_MAX_SS];
    MKFS_PARM opt;
    opt.fmt = FM_FAT | FM_SFD;
    opt.n_fat = 1;
    opt.align = 1;
    opt.n_root = 16;
    opt.au_size = 512;

    // EEPROMマウント
    if ((stat_f = f_mount(&FatFSEeprom, "0:", 1)) != FR_OK) {
        printf("EEPROM disk mount failed with %d.\n", stat_f);
        printf("Formatting...");
        // stat_f = f_mkfs("0:", &opt, work, sizeof(work));
        stat_f = FR_NOT_ENABLED;
        if (stat_f != FR_OK) {
            printf("Failed (%u).\n", stat_f);
            error_blink();
        } else {
            printf("Completed.\n");
            stat_f = f_mount(&FatFSEeprom, "0:", 1);
            if (stat_f == FR_OK) {
                printf("re:Mount OK.\n");
            } else {
                printf("re:Mount Failure.\n");
                error_blink();
            }
        }
    } else {
        printf("EEPROM disk mount OK.\n");
    }

    return true;
}

// メモリーダンプ(EEPROM)
void EEPROM_dump(uint adrs, uint len)
{
    uint8_t dat;
    uint8_t str[17] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 0};

    if (!eeprom) return;

    while (len > 0) {
        if ((adrs & 0x0f) == 0) {
            printf("%04X  ", adrs);
        } else if ((adrs & 0x0f) == 0x08) {
            printf(" ");
        }
        dat = eeprom->read_byte(adrs);
        if ((dat >= ' ') && (dat <= 0x7f)) {
            str[adrs&0x0f] = dat;
        } else {
            str[adrs&0x0f] = '.';
        }
        printf("%02X ", dat);
        if ((adrs & 0x0f) == 0x0f) {
            printf("%s\n", str);
        }
        adrs++;
        len--;
    }
    if ((adrs & 0x0f) < 0x0f) {
        str[adrs&0x0f+1] = 0;
        printf("%s", str);
    }
    if ((adrs & 0x0f) != 0x0) {
        printf("\n");
    }
}

void test_filesystem(void)
{
    // ファイルリードライトテスト
    FIL file;
    FRESULT result;
    TCHAR buf[128] = {0};
    const char *expected = "Hello, world!\n";
/*
    result = f_open(&file, "hello.txt", FA_WRITE | FA_CREATE_ALWAYS);
    if (result != FR_OK) {
        printf("file write open failure (%u).\n", result);
        error_blink();
    }
    if (f_printf(&file, "%s", expected) < 0 || f_close(&file) != FR_OK) {
        printf("file write failure.\n");
        error_blink();
    }
*/
    result = f_open(&file, "0:/hello.txt", FA_READ);
    if (result != FR_OK) {
        printf("file read open failure (%u).\n", result);
        // error_blink();
    } else {
        while (f_gets(buf, sizeof(buf), &file) != NULL) {
            printf("%s\n", buf);
        }
        f_close(&file);
        printf("File W/R test OK.\n");
    }

    // ディレクトリ表示
    FRESULT res;
    DIR dir;
    FILINFO fno;
    int nfile, ndir;
    const char *path = "0:/";

    res = f_opendir(&dir, path);
    if (res == FR_OK) {
        nfile = ndir = 0;
        for (;;) {
            res = f_readdir(&dir, &fno);
            if (fno.fname[0] == 0) break;
            if (fno.fattrib & AM_DIR) {
                printf("   <DIR>   %s\n", fno.fname);
                ndir++;
            } else {
                printf("%10u %s\n", fno.fsize, fno.fname);
                nfile++;
            }
        }
        f_closedir(&dir);
        printf("%d dirs, %d files.\n", ndir, nfile);
    } else {
        printf("Failed to open \"%s\". (%u)\n", path, res);
    }

}

完成版ファイル・ダウンロード / サポート

この続きはcodocで購読