/programy/C/avr/SDcard/Makefile |
---|
0,0 → 1,61 |
# makefile, written by guido socher |
MCU=atmega64 |
CC=avr-gcc |
OBJCOPY=avr-objcopy |
# optimize for size: |
CFLAGS=-g -mmcu=$(MCU) -Wall -Wstrict-prototypes -Os -mcall-prologues |
#------------------- |
all: main.hex |
#------------------- |
help: |
@echo "Usage: make all|load|load_pre|rdfuses|wrfuse1mhz|wrfuse4mhz|wrfusecrystal" |
@echo "Warning: you will not be able to undo wrfusecrystal unless you connect an" |
@echo " external crystal! uC is dead after wrfusecrystal if you do not" |
@echo " have an external crystal." |
#------------------- |
main.hex : main.out |
$(OBJCOPY) -R .eeprom -O ihex main.out main.hex |
main.out : main.o |
$(CC) $(CFLAGS) -o main.out -Wl,-Map,main.map main.o |
main.o : main.c |
$(CC) $(CFLAGS) -Os -c main.c |
#------------------ |
load: $(FILE).hex |
./prg_load_uc $(FILE).hex |
# here is a pre-compiled version in case you have trouble with |
# your development environment |
load_pre: $(FILE).hex |
./prg_load_uc $(FILE)_pre.hex |
# |
loaduisp: $(FILE).hex |
./prg_load_uc -u $(FILE).hex |
# here is a pre-compiled version in case you have trouble with |
# your development environment |
load_preuisp: $(FILE)_pre.hex |
./prg_load_uc -u avrm8ledtest.hex |
#------------------- |
# fuse byte settings: |
# Atmel AVR ATmega8 |
# Fuse Low Byte = 0xe1 (1MHz internal), 0xe3 (4MHz internal), 0xe4 (8MHz internal) |
# Fuse High Byte = 0xd9 |
# Factory default is 0xe1 for low byte and 0xd9 for high byte |
# Check this with make rdfuses |
rdfuses: |
./prg_fusebit_uc -r |
# use internal RC oscillator 1 Mhz |
wrfuse1mhz: |
./prg_fusebit_uc -w 1 |
# use internal RC oscillator 4 Mhz |
wrfuse4mhz: |
./prg_fusebit_uc -w 4 |
# use external 3-8 Mhz crystal |
# Warning: you can not reset this to intenal unless you connect a crystal!! |
wrfusecrystal: |
@echo "Warning: The external crystal setting can not be changed back without a working crystal" |
@echo " You have 3 seconds to abort this with crtl-c" |
@sleep 3 |
./prg_fusebit_uc -w 0 |
#------------------- |
clean: |
rm -f *.o *.map *.out *.hex |
#------------------- |
/programy/C/avr/SDcard/diskio.h |
---|
0,0 → 1,71 |
/*----------------------------------------------------------------------- |
/ Low level disk interface modlue include file R0.05 (C)ChaN, 2007 |
/-----------------------------------------------------------------------*/ |
#ifndef _DISKIO |
#define _READONLY 0 /* 1: Read-only mode */ |
#define _USE_IOCTL 1 |
#include "integer.h" |
/* Status of Disk Functions */ |
typedef BYTE DSTATUS; |
/* Results of Disk Functions */ |
typedef enum { |
RES_OK = 0, /* 0: Successful */ |
RES_ERROR, /* 1: R/W Error */ |
RES_WRPRT, /* 2: Write Protected */ |
RES_NOTRDY, /* 3: Not Ready */ |
RES_PARERR /* 4: Invalid Parameter */ |
} DRESULT; |
/*---------------------------------------*/ |
/* Prototypes for disk control functions */ |
DSTATUS disk_initialize (BYTE); |
DSTATUS disk_status (BYTE); |
DRESULT disk_read (BYTE, BYTE*, DWORD, BYTE); |
#if _READONLY == 0 |
DRESULT disk_write (BYTE, const BYTE*, DWORD, BYTE); |
#endif |
DRESULT disk_ioctl (BYTE, BYTE, void*); |
void disk_timerproc (void); |
/* Disk Status Bits (DSTATUS) */ |
#define STA_NOINIT 0x01 /* Drive not initialized */ |
#define STA_NODISK 0x02 /* No medium in the drive */ |
#define STA_PROTECT 0x04 /* Write protected */ |
/* Command code for disk_ioctrl() */ |
/* Generic command */ |
#define CTRL_SYNC 0 /* Mandatory for write functions */ |
#define GET_SECTOR_COUNT 1 /* Mandatory for only f_mkfs() */ |
#define GET_SECTOR_SIZE 2 |
#define GET_BLOCK_SIZE 3 /* Mandatory for only f_mkfs() */ |
#define CTRL_POWER 4 |
#define CTRL_LOCK 5 |
#define CTRL_EJECT 6 |
/* MMC/SDC command */ |
#define MMC_GET_TYPE 10 |
#define MMC_GET_CSD 11 |
#define MMC_GET_CID 12 |
#define MMC_GET_OCR 13 |
#define MMC_GET_SDSTAT 14 |
/* ATA/CF command */ |
#define ATA_GET_REV 20 |
#define ATA_GET_MODEL 21 |
#define ATA_GET_SN 22 |
#define _DISKIO |
#endif |
/programy/C/avr/SDcard/ff.c |
---|
0,0 → 1,2036 |
/*----------------------------------------------------------------------------/ |
/ FatFs - FAT file system module R0.06 (C)ChaN, 2008 |
/-----------------------------------------------------------------------------/ |
/ The FatFs module is an experimenal project to implement FAT file system to |
/ cheap microcontrollers. This is a free software and is opened for education, |
/ research and development under license policy of following trems. |
/ |
/ Copyright (C) 2008, ChaN, all right reserved. |
/ |
/ * The FatFs module is a free software and there is no warranty. |
/ * You can use, modify and/or redistribute it for personal, non-profit or |
/ commercial use without restriction under your responsibility. |
/ * Redistributions of source code must retain the above copyright notice. |
/ |
/-----------------------------------------------------------------------------/ |
/ Feb 26,'06 R0.00 Prototype. |
/ |
/ Apr 29,'06 R0.01 First stable version. |
/ |
/ Jun 01,'06 R0.02 Added FAT12 support. |
/ Removed unbuffered mode. |
/ Fixed a problem on small (<32M) patition. |
/ Jun 10,'06 R0.02a Added a configuration option (_FS_MINIMUM). |
/ |
/ Sep 22,'06 R0.03 Added f_rename(). |
/ Changed option _FS_MINIMUM to _FS_MINIMIZE. |
/ Dec 11,'06 R0.03a Improved cluster scan algolithm to write files fast. |
/ Fixed f_mkdir() creates incorrect directory on FAT32. |
/ |
/ Feb 04,'07 R0.04 Supported multiple drive system. |
/ Changed some interfaces for multiple drive system. |
/ Changed f_mountdrv() to f_mount(). |
/ Added f_mkfs(). |
/ Apr 01,'07 R0.04a Supported multiple partitions on a plysical drive. |
/ Added a capability of extending file size to f_lseek(). |
/ Added minimization level 3. |
/ Fixed an endian sensitive code in f_mkfs(). |
/ May 05,'07 R0.04b Added a configuration option _USE_NTFLAG. |
/ Added FSInfo support. |
/ Fixed DBCS name can result FR_INVALID_NAME. |
/ Fixed short seek (<= csize) collapses the file object. |
/ |
/ Aug 25,'07 R0.05 Changed arguments of f_read(), f_write() and f_mkfs(). |
/ Fixed f_mkfs() on FAT32 creates incorrect FSInfo. |
/ Fixed f_mkdir() on FAT32 creates incorrect directory. |
/ Feb 03,'08 R0.05a Added f_truncate() and f_utime(). |
/ Fixed off by one error at FAT sub-type determination. |
/ Fixed btr in f_read() can be mistruncated. |
/ Fixed cached sector is not flushed when create and close |
/ without write. |
/ |
/ Apr 01,'08 R0.06 Added fputc(), fputs(), fprintf() and fgets(). |
/ Improved performance of f_lseek() on moving to the same |
/ or following cluster. |
/---------------------------------------------------------------------------*/ |
#include <string.h> |
#include "ff.h" /* FatFs declarations */ |
#include "diskio.h" /* Include file for user provided disk functions */ |
/*-------------------------------------------------------------------------- |
Module Private Functions |
---------------------------------------------------------------------------*/ |
static |
FATFS *FatFs[_DRIVES]; /* Pointer to the file system objects (logical drives) */ |
static |
WORD fsid; /* File system mount ID */ |
/*-----------------------------------------------------------------------*/ |
/* Change window offset */ |
/*-----------------------------------------------------------------------*/ |
static |
BOOL move_window ( /* TRUE: successful, FALSE: failed */ |
FATFS *fs, /* File system object */ |
DWORD sector /* Sector number to make apperance in the fs->win[] */ |
) /* Move to zero only writes back dirty window */ |
{ |
DWORD wsect; |
wsect = fs->winsect; |
if (wsect != sector) { /* Changed current window */ |
#if !_FS_READONLY |
BYTE n; |
if (fs->winflag) { /* Write back dirty window if needed */ |
if (disk_write(fs->drive, fs->win, wsect, 1) != RES_OK) |
return FALSE; |
fs->winflag = 0; |
if (wsect < (fs->fatbase + fs->sects_fat)) { /* In FAT area */ |
for (n = fs->n_fats; n >= 2; n--) { /* Refrect the change to FAT copy */ |
wsect += fs->sects_fat; |
disk_write(fs->drive, fs->win, wsect, 1); |
} |
} |
} |
#endif |
if (sector) { |
if (disk_read(fs->drive, fs->win, sector, 1) != RES_OK) |
return FALSE; |
fs->winsect = sector; |
} |
} |
return TRUE; |
} |
/*-----------------------------------------------------------------------*/ |
/* Clean-up cached data */ |
/*-----------------------------------------------------------------------*/ |
#if !_FS_READONLY |
static |
FRESULT sync ( /* FR_OK: successful, FR_RW_ERROR: failed */ |
FATFS *fs /* File system object */ |
) |
{ |
fs->winflag = 1; |
if (!move_window(fs, 0)) return FR_RW_ERROR; |
#if _USE_FSINFO |
/* Update FSInfo sector if needed */ |
if (fs->fs_type == FS_FAT32 && fs->fsi_flag) { |
fs->winsect = 0; |
memset(fs->win, 0, 512); |
ST_WORD(&fs->win[BS_55AA], 0xAA55); |
ST_DWORD(&fs->win[FSI_LeadSig], 0x41615252); |
ST_DWORD(&fs->win[FSI_StrucSig], 0x61417272); |
ST_DWORD(&fs->win[FSI_Free_Count], fs->free_clust); |
ST_DWORD(&fs->win[FSI_Nxt_Free], fs->last_clust); |
disk_write(fs->drive, fs->win, fs->fsi_sector, 1); |
fs->fsi_flag = 0; |
} |
#endif |
/* Make sure that no pending write process in the physical drive */ |
if (disk_ioctl(fs->drive, CTRL_SYNC, NULL) != RES_OK) |
return FR_RW_ERROR; |
return FR_OK; |
} |
#endif |
/*-----------------------------------------------------------------------*/ |
/* Get a cluster status */ |
/*-----------------------------------------------------------------------*/ |
static |
DWORD get_cluster ( /* 0,>=2: successful, 1: failed */ |
FATFS *fs, /* File system object */ |
DWORD clust /* Cluster# to get the link information */ |
) |
{ |
WORD wc, bc; |
DWORD fatsect; |
if (clust >= 2 && clust < fs->max_clust) { /* Is it a valid cluster#? */ |
fatsect = fs->fatbase; |
switch (fs->fs_type) { |
case FS_FAT12 : |
bc = (WORD)clust * 3 / 2; |
if (!move_window(fs, fatsect + (bc / SS(fs)))) break; |
wc = fs->win[bc & (SS(fs) - 1)]; bc++; |
if (!move_window(fs, fatsect + (bc / SS(fs)))) break; |
wc |= (WORD)fs->win[bc & (SS(fs) - 1)] << 8; |
return (clust & 1) ? (wc >> 4) : (wc & 0xFFF); |
case FS_FAT16 : |
if (!move_window(fs, fatsect + (clust / (SS(fs) / 2)))) break; |
return LD_WORD(&fs->win[((WORD)clust * 2) & (SS(fs) - 1)]); |
case FS_FAT32 : |
if (!move_window(fs, fatsect + (clust / (SS(fs) / 4)))) break; |
return LD_DWORD(&fs->win[((WORD)clust * 4) & (SS(fs) - 1)]) & 0x0FFFFFFF; |
} |
} |
return 1; /* Out of cluster range, or an error occured */ |
} |
/*-----------------------------------------------------------------------*/ |
/* Change a cluster status */ |
/*-----------------------------------------------------------------------*/ |
#if !_FS_READONLY |
static |
BOOL put_cluster ( /* TRUE: successful, FALSE: failed */ |
FATFS *fs, /* File system object */ |
DWORD clust, /* Cluster# to change (must be 2 to fs->max_clust-1) */ |
DWORD val /* New value to mark the cluster */ |
) |
{ |
WORD bc; |
BYTE *p; |
DWORD fatsect; |
fatsect = fs->fatbase; |
switch (fs->fs_type) { |
case FS_FAT12 : |
bc = (WORD)clust * 3 / 2; |
if (!move_window(fs, fatsect + (bc / SS(fs)))) return FALSE; |
p = &fs->win[bc & (SS(fs) - 1)]; |
*p = (clust & 1) ? ((*p & 0x0F) | ((BYTE)val << 4)) : (BYTE)val; |
bc++; |
fs->winflag = 1; |
if (!move_window(fs, fatsect + (bc / SS(fs)))) return FALSE; |
p = &fs->win[bc & (SS(fs) - 1)]; |
*p = (clust & 1) ? (BYTE)(val >> 4) : ((*p & 0xF0) | ((BYTE)(val >> 8) & 0x0F)); |
break; |
case FS_FAT16 : |
if (!move_window(fs, fatsect + (clust / (SS(fs) / 2)))) return FALSE; |
ST_WORD(&fs->win[((WORD)clust * 2) & (SS(fs) - 1)], (WORD)val); |
break; |
case FS_FAT32 : |
if (!move_window(fs, fatsect + (clust / (SS(fs) / 4)))) return FALSE; |
ST_DWORD(&fs->win[((WORD)clust * 4) & (SS(fs) - 1)], val); |
break; |
default : |
return FALSE; |
} |
fs->winflag = 1; |
return TRUE; |
} |
#endif /* !_FS_READONLY */ |
/*-----------------------------------------------------------------------*/ |
/* Remove a cluster chain */ |
/*-----------------------------------------------------------------------*/ |
#if !_FS_READONLY |
static |
BOOL remove_chain ( /* TRUE: successful, FALSE: failed */ |
FATFS *fs, /* File system object */ |
DWORD clust /* Cluster# to remove chain from */ |
) |
{ |
DWORD nxt; |
while (clust >= 2 && clust < fs->max_clust) { |
nxt = get_cluster(fs, clust); |
if (nxt == 1) return FALSE; |
if (!put_cluster(fs, clust, 0)) return FALSE; |
if (fs->free_clust != 0xFFFFFFFF) { |
fs->free_clust++; |
#if _USE_FSINFO |
fs->fsi_flag = 1; |
#endif |
} |
clust = nxt; |
} |
return TRUE; |
} |
#endif |
/*-----------------------------------------------------------------------*/ |
/* Stretch or create a cluster chain */ |
/*-----------------------------------------------------------------------*/ |
#if !_FS_READONLY |
static |
DWORD create_chain ( /* 0: No free cluster, 1: Error, >=2: New cluster number */ |
FATFS *fs, /* File system object */ |
DWORD clust /* Cluster# to stretch, 0 means create new */ |
) |
{ |
DWORD cstat, ncl, scl, mcl = fs->max_clust; |
if (clust == 0) { /* Create new chain */ |
scl = fs->last_clust; /* Get suggested start point */ |
if (scl == 0 || scl >= mcl) scl = 1; |
} |
else { /* Stretch existing chain */ |
cstat = get_cluster(fs, clust); /* Check the cluster status */ |
if (cstat < 2) return 1; /* It is an invalid cluster */ |
if (cstat < mcl) return cstat; /* It is already followed by next cluster */ |
scl = clust; |
} |
ncl = scl; /* Start cluster */ |
for (;;) { |
ncl++; /* Next cluster */ |
if (ncl >= mcl) { /* Wrap around */ |
ncl = 2; |
if (ncl > scl) return 0; /* No free custer */ |
} |
cstat = get_cluster(fs, ncl); /* Get the cluster status */ |
if (cstat == 0) break; /* Found a free cluster */ |
if (cstat == 1) return 1; /* Any error occured */ |
if (ncl == scl) return 0; /* No free custer */ |
} |
if (!put_cluster(fs, ncl, 0x0FFFFFFF)) return 1; /* Mark the new cluster "in use" */ |
if (clust != 0 && !put_cluster(fs, clust, ncl)) return 1; /* Link it to previous one if needed */ |
fs->last_clust = ncl; /* Update fsinfo */ |
if (fs->free_clust != 0xFFFFFFFF) { |
fs->free_clust--; |
#if _USE_FSINFO |
fs->fsi_flag = 1; |
#endif |
} |
return ncl; /* Return new cluster number */ |
} |
#endif /* !_FS_READONLY */ |
/*-----------------------------------------------------------------------*/ |
/* Get sector# from cluster# */ |
/*-----------------------------------------------------------------------*/ |
static |
DWORD clust2sect ( /* !=0: sector number, 0: failed - invalid cluster# */ |
FATFS *fs, /* File system object */ |
DWORD clust /* Cluster# to be converted */ |
) |
{ |
clust -= 2; |
if (clust >= (fs->max_clust - 2)) return 0; /* Invalid cluster# */ |
return clust * fs->csize + fs->database; |
} |
/*-----------------------------------------------------------------------*/ |
/* Move directory pointer to next */ |
/*-----------------------------------------------------------------------*/ |
static |
BOOL next_dir_entry ( /* TRUE: successful, FALSE: could not move next */ |
DIR *dj /* Pointer to directory object */ |
) |
{ |
DWORD clust; |
WORD idx; |
idx = dj->index + 1; |
if ((idx & ((SS(dj->fs) - 1) / 32)) == 0) { /* Table sector changed? */ |
dj->sect++; /* Next sector */ |
if (dj->clust == 0) { /* In static table */ |
if (idx >= dj->fs->n_rootdir) return FALSE; /* Reached to end of table */ |
} else { /* In dynamic table */ |
if (((idx / (SS(dj->fs) / 32)) & (dj->fs->csize - 1)) == 0) { /* Cluster changed? */ |
clust = get_cluster(dj->fs, dj->clust); /* Get next cluster */ |
if (clust < 2 || clust >= dj->fs->max_clust) /* Reached to end of table */ |
return FALSE; |
dj->clust = clust; /* Initialize for new cluster */ |
dj->sect = clust2sect(dj->fs, clust); |
} |
} |
} |
dj->index = idx; /* Lower several bits of dj->index indicates offset in dj->sect */ |
return TRUE; |
} |
/*-----------------------------------------------------------------------*/ |
/* Get file status from directory entry */ |
/*-----------------------------------------------------------------------*/ |
#if _FS_MINIMIZE <= 1 |
static |
void get_fileinfo ( /* No return code */ |
FILINFO *finfo, /* Ptr to store the file information */ |
const BYTE *dir /* Ptr to the directory entry */ |
) |
{ |
BYTE n, c, a; |
char *p; |
p = &finfo->fname[0]; |
a = _USE_NTFLAG ? dir[DIR_NTres] : 0; /* NT flag */ |
for (n = 0; n < 8; n++) { /* Convert file name (body) */ |
c = dir[n]; |
if (c == ' ') break; |
if (c == 0x05) c = 0xE5; |
if (a & 0x08 && c >= 'A' && c <= 'Z') c += 0x20; |
*p++ = c; |
} |
if (dir[8] != ' ') { /* Convert file name (extension) */ |
*p++ = '.'; |
for (n = 8; n < 11; n++) { |
c = dir[n]; |
if (c == ' ') break; |
if (a & 0x10 && c >= 'A' && c <= 'Z') c += 0x20; |
*p++ = c; |
} |
} |
*p = '\0'; |
finfo->fattrib = dir[DIR_Attr]; /* Attribute */ |
finfo->fsize = LD_DWORD(&dir[DIR_FileSize]); /* Size */ |
finfo->fdate = LD_WORD(&dir[DIR_WrtDate]); /* Date */ |
finfo->ftime = LD_WORD(&dir[DIR_WrtTime]); /* Time */ |
} |
#endif /* _FS_MINIMIZE <= 1 */ |
/*-----------------------------------------------------------------------*/ |
/* Pick a paragraph and create the name in format of directory entry */ |
/*-----------------------------------------------------------------------*/ |
static |
char make_dirfile ( /* 1: error - detected an invalid format, '\0'or'/': next character */ |
const char **path, /* Pointer to the file path pointer */ |
char *dirname /* Pointer to directory name buffer {Name(8), Ext(3), NT flag(1)} */ |
) |
{ |
BYTE n, t, c, a, b; |
memset(dirname, ' ', 8+3); /* Fill buffer with spaces */ |
a = 0; b = 0x18; /* NT flag */ |
n = 0; t = 8; |
for (;;) { |
c = *(*path)++; |
if (c == '\0' || c == '/') { /* Reached to end of str or directory separator */ |
if (n == 0) break; |
dirname[11] = _USE_NTFLAG ? (a & b) : 0; |
return c; |
} |
if (c <= ' ' || c == 0x7F) break; /* Reject invisible chars */ |
if (c == '.') { |
if (!(a & 1) && n >= 1 && n <= 8) { /* Enter extension part */ |
n = 8; t = 11; continue; |
} |
break; |
} |
if (_USE_SJIS && |
((c >= 0x81 && c <= 0x9F) || /* Accept S-JIS code */ |
(c >= 0xE0 && c <= 0xFC))) { |
if (n == 0 && c == 0xE5) /* Change heading \xE5 to \x05 */ |
c = 0x05; |
a ^= 0x01; goto md_l2; |
} |
if (c == '"') break; /* Reject " */ |
if (c <= ')') goto md_l1; /* Accept ! # $ % & ' ( ) */ |
if (c <= ',') break; /* Reject * + , */ |
if (c <= '9') goto md_l1; /* Accept - 0-9 */ |
if (c <= '?') break; /* Reject : ; < = > ? */ |
if (!(a & 1)) { /* These checks are not applied to S-JIS 2nd byte */ |
if (c == '|') break; /* Reject | */ |
if (c >= '[' && c <= ']') break;/* Reject [ \ ] */ |
if (_USE_NTFLAG && c >= 'A' && c <= 'Z') |
(t == 8) ? (b &= 0xF7) : (b &= 0xEF); |
if (c >= 'a' && c <= 'z') { /* Convert to upper case */ |
c -= 0x20; |
if (_USE_NTFLAG) (t == 8) ? (a |= 0x08) : (a |= 0x10); |
} |
} |
md_l1: |
a &= 0xFE; |
md_l2: |
if (n >= t) break; |
dirname[n++] = c; |
} |
return 1; |
} |
/*-----------------------------------------------------------------------*/ |
/* Trace a file path */ |
/*-----------------------------------------------------------------------*/ |
static |
FRESULT trace_path ( /* FR_OK(0): successful, !=0: error code */ |
DIR *dj, /* Pointer to directory object to return last directory */ |
char *fn, /* Pointer to last segment name to return {file(8),ext(3),attr(1)} */ |
const char *path, /* Full-path string to trace a file or directory */ |
BYTE **dir /* Pointer to pointer to found entry to retutn */ |
) |
{ |
DWORD clust; |
char ds; |
BYTE *dptr = NULL; |
FATFS *fs = dj->fs; |
/* Initialize directory object */ |
clust = fs->dirbase; |
if (fs->fs_type == FS_FAT32) { |
dj->clust = dj->sclust = clust; |
dj->sect = clust2sect(fs, clust); |
} else { |
dj->clust = dj->sclust = 0; |
dj->sect = clust; |
} |
dj->index = 0; |
if (*path == '\0') { /* Null path means the root directory */ |
*dir = NULL; return FR_OK; |
} |
for (;;) { |
ds = make_dirfile(&path, fn); /* Get a paragraph into fn[] */ |
if (ds == 1) return FR_INVALID_NAME; |
for (;;) { |
if (!move_window(fs, dj->sect)) return FR_RW_ERROR; |
dptr = &fs->win[(dj->index & ((SS(fs) - 1) / 32)) * 32]; /* Pointer to the directory entry */ |
if (dptr[DIR_Name] == 0) /* Has it reached to end of dir? */ |
return !ds ? FR_NO_FILE : FR_NO_PATH; |
if (dptr[DIR_Name] != 0xE5 /* Matched? */ |
&& !(dptr[DIR_Attr] & AM_VOL) |
&& !memcmp(&dptr[DIR_Name], fn, 8+3) ) break; |
if (!next_dir_entry(dj)) /* Next directory pointer */ |
return !ds ? FR_NO_FILE : FR_NO_PATH; |
} |
if (!ds) { *dir = dptr; return FR_OK; } /* Matched with end of path */ |
if (!(dptr[DIR_Attr] & AM_DIR)) return FR_NO_PATH; /* Cannot trace because it is a file */ |
clust = ((DWORD)LD_WORD(&dptr[DIR_FstClusHI]) << 16) | LD_WORD(&dptr[DIR_FstClusLO]); /* Get cluster# of the directory */ |
dj->clust = dj->sclust = clust; /* Restart scanning at the new directory */ |
dj->sect = clust2sect(fs, clust); |
dj->index = 2; |
} |
} |
/*-----------------------------------------------------------------------*/ |
/* Reserve a directory entry */ |
/*-----------------------------------------------------------------------*/ |
#if !_FS_READONLY |
static |
FRESULT reserve_direntry ( /* FR_OK: successful, FR_DENIED: no free entry, FR_RW_ERROR: a disk error occured */ |
DIR *dj, /* Target directory to create new entry */ |
BYTE **dir /* Pointer to pointer to created entry to retutn */ |
) |
{ |
DWORD clust, sector; |
BYTE c, n, *dptr; |
FATFS *fs = dj->fs; |
/* Re-initialize directory object */ |
clust = dj->sclust; |
if (clust != 0) { /* Dyanmic directory table */ |
dj->clust = clust; |
dj->sect = clust2sect(fs, clust); |
} else { /* Static directory table */ |
dj->sect = fs->dirbase; |
} |
dj->index = 0; |
do { |
if (!move_window(fs, dj->sect)) return FR_RW_ERROR; |
dptr = &fs->win[(dj->index & ((SS(dj->fs) - 1) / 32)) * 32]; /* Pointer to the directory entry */ |
c = dptr[DIR_Name]; |
if (c == 0 || c == 0xE5) { /* Found an empty entry */ |
*dir = dptr; return FR_OK; |
} |
} while (next_dir_entry(dj)); /* Next directory pointer */ |
/* Reached to end of the directory table */ |
/* Abort when it is a static table or could not stretch dynamic table */ |
if (clust == 0 || !(clust = create_chain(fs, dj->clust))) return FR_DENIED; |
if (clust == 1 || !move_window(fs, 0)) return FR_RW_ERROR; |
/* Cleanup the expanded table */ |
fs->winsect = sector = clust2sect(fs, clust); |
memset(fs->win, 0, SS(fs)); |
for (n = fs->csize; n; n--) { |
if (disk_write(fs->drive, fs->win, sector, 1) != RES_OK) |
return FR_RW_ERROR; |
sector++; |
} |
fs->winflag = 1; |
*dir = fs->win; |
return FR_OK; |
} |
#endif /* !_FS_READONLY */ |
/*-----------------------------------------------------------------------*/ |
/* Load boot record and check if it is an FAT boot record */ |
/*-----------------------------------------------------------------------*/ |
static |
BYTE check_fs ( /* 0:The FAT boot record, 1:Valid boot record but not an FAT, 2:Not a boot record or error */ |
FATFS *fs, /* File system object */ |
DWORD sect /* Sector# (lba) to check if it is an FAT boot record or not */ |
) |
{ |
if (disk_read(fs->drive, fs->win, sect, 1) != RES_OK) /* Load boot record */ |
return 2; |
if (LD_WORD(&fs->win[BS_55AA]) != 0xAA55) /* Check record signature (always placed at offset 510 even if the sector size is >512) */ |
return 2; |
if (!memcmp(&fs->win[BS_FilSysType], "FAT", 3)) /* Check FAT signature */ |
return 0; |
if (!memcmp(&fs->win[BS_FilSysType32], "FAT32", 5) && !(fs->win[BPB_ExtFlags] & 0x80)) |
return 0; |
return 1; |
} |
/*-----------------------------------------------------------------------*/ |
/* Make sure that the file system is valid */ |
/*-----------------------------------------------------------------------*/ |
static |
FRESULT auto_mount ( /* FR_OK(0): successful, !=0: any error occured */ |
const char **path, /* Pointer to pointer to the path name (drive number) */ |
FATFS **rfs, /* Pointer to pointer to the found file system object */ |
BYTE chk_wp /* !=0: Check media write protection for write access */ |
) |
{ |
BYTE drv, fmt, *tbl; |
DSTATUS stat; |
DWORD bootsect, fatsize, totalsect, maxclust; |
const char *p = *path; |
FATFS *fs; |
/* Get drive number from the path name */ |
while (*p == ' ') p++; /* Strip leading spaces */ |
drv = p[0] - '0'; /* Is there a drive number? */ |
if (drv <= 9 && p[1] == ':') |
p += 2; /* Found a drive number, get and strip it */ |
else |
drv = 0; /* No drive number is given, use drive number 0 as default */ |
if (*p == '/') p++; /* Strip heading slash */ |
*path = p; /* Return pointer to the path name */ |
/* Check if the drive number is valid or not */ |
if (drv >= _DRIVES) return FR_INVALID_DRIVE; /* Is the drive number valid? */ |
*rfs = fs = FatFs[drv]; /* Returen pointer to the corresponding file system object */ |
if (!fs) return FR_NOT_ENABLED; /* Is the file system object registered? */ |
if (fs->fs_type) { /* If the logical drive has been mounted */ |
stat = disk_status(fs->drive); |
if (!(stat & STA_NOINIT)) { /* and physical drive is kept initialized (has not been changed), */ |
#if !_FS_READONLY |
if (chk_wp && (stat & STA_PROTECT)) /* Check write protection if needed */ |
return FR_WRITE_PROTECTED; |
#endif |
return FR_OK; /* The file system object is valid */ |
} |
} |
/* The logical drive must be re-mounted. Following code attempts to mount the logical drive */ |
memset(fs, 0, sizeof(FATFS)); /* Clean-up the file system object */ |
fs->drive = LD2PD(drv); /* Bind the logical drive and a physical drive */ |
stat = disk_initialize(fs->drive); /* Initialize low level disk I/O layer */ |
if (stat & STA_NOINIT) /* Check if the drive is ready */ |
return FR_NOT_READY; |
#if S_MAX_SIZ > 512 /* Get disk sector size if needed */ |
if (disk_ioctl(drv, GET_SECTOR_SIZE, &SS(fs)) != RES_OK || SS(fs) > S_MAX_SIZ) |
return FR_NO_FILESYSTEM; |
#endif |
#if !_FS_READONLY |
if (chk_wp && (stat & STA_PROTECT)) /* Check write protection if needed */ |
return FR_WRITE_PROTECTED; |
#endif |
/* Search FAT partition on the drive */ |
fmt = check_fs(fs, bootsect = 0); /* Check sector 0 as an SFD format */ |
if (fmt == 1) { /* Not an FAT boot record, it may be patitioned */ |
/* Check a partition listed in top of the partition table */ |
tbl = &fs->win[MBR_Table + LD2PT(drv) * 16]; /* Partition table */ |
if (tbl[4]) { /* Is the partition existing? */ |
bootsect = LD_DWORD(&tbl[8]); /* Partition offset in LBA */ |
fmt = check_fs(fs, bootsect); /* Check the partition */ |
} |
} |
if (fmt || LD_WORD(&fs->win[BPB_BytsPerSec]) != SS(fs)) /* No valid FAT patition is found */ |
return FR_NO_FILESYSTEM; |
/* Initialize the file system object */ |
fatsize = LD_WORD(&fs->win[BPB_FATSz16]); /* Number of sectors per FAT */ |
if (!fatsize) fatsize = LD_DWORD(&fs->win[BPB_FATSz32]); |
fs->sects_fat = fatsize; |
fs->n_fats = fs->win[BPB_NumFATs]; /* Number of FAT copies */ |
fatsize *= fs->n_fats; /* (Number of sectors in FAT area) */ |
fs->fatbase = bootsect + LD_WORD(&fs->win[BPB_RsvdSecCnt]); /* FAT start sector (lba) */ |
fs->csize = fs->win[BPB_SecPerClus]; /* Number of sectors per cluster */ |
fs->n_rootdir = LD_WORD(&fs->win[BPB_RootEntCnt]); /* Nmuber of root directory entries */ |
totalsect = LD_WORD(&fs->win[BPB_TotSec16]); /* Number of sectors on the file system */ |
if (!totalsect) totalsect = LD_DWORD(&fs->win[BPB_TotSec32]); |
fs->max_clust = maxclust = (totalsect /* max_clust = Last cluster# + 1 */ |
- LD_WORD(&fs->win[BPB_RsvdSecCnt]) - fatsize - fs->n_rootdir / (SS(fs)/32) |
) / fs->csize + 2; |
fmt = FS_FAT12; /* Determine the FAT sub type */ |
if (maxclust >= 0xFF7) fmt = FS_FAT16; |
if (maxclust >= 0xFFF7) fmt = FS_FAT32; |
if (fmt == FS_FAT32) |
fs->dirbase = LD_DWORD(&fs->win[BPB_RootClus]); /* Root directory start cluster */ |
else |
fs->dirbase = fs->fatbase + fatsize; /* Root directory start sector (lba) */ |
fs->database = fs->fatbase + fatsize + fs->n_rootdir / (SS(fs)/32); /* Data start sector (lba) */ |
#if !_FS_READONLY |
/* Initialize allocation information */ |
fs->free_clust = 0xFFFFFFFF; |
#if _USE_FSINFO |
/* Get fsinfo if needed */ |
if (fmt == FS_FAT32) { |
fs->fsi_sector = bootsect + LD_WORD(&fs->win[BPB_FSInfo]); |
if (disk_read(fs->drive, fs->win, fs->fsi_sector, 1) == RES_OK && |
LD_WORD(&fs->win[BS_55AA]) == 0xAA55 && |
LD_DWORD(&fs->win[FSI_LeadSig]) == 0x41615252 && |
LD_DWORD(&fs->win[FSI_StrucSig]) == 0x61417272) { |
fs->last_clust = LD_DWORD(&fs->win[FSI_Nxt_Free]); |
fs->free_clust = LD_DWORD(&fs->win[FSI_Free_Count]); |
} |
} |
#endif |
#endif |
fs->fs_type = fmt; /* FAT syb-type */ |
fs->id = ++fsid; /* File system mount ID */ |
return FR_OK; |
} |
/*-----------------------------------------------------------------------*/ |
/* Check if the file/dir object is valid or not */ |
/*-----------------------------------------------------------------------*/ |
static |
FRESULT validate ( /* FR_OK(0): The object is valid, !=0: Invalid */ |
const FATFS *fs, /* Pointer to the file system object */ |
WORD id /* Member id of the target object to be checked */ |
) |
{ |
if (!fs || !fs->fs_type || fs->id != id) |
return FR_INVALID_OBJECT; |
if (disk_status(fs->drive) & STA_NOINIT) |
return FR_NOT_READY; |
return FR_OK; |
} |
/*-------------------------------------------------------------------------- |
Public Functions |
--------------------------------------------------------------------------*/ |
/*-----------------------------------------------------------------------*/ |
/* Mount/Unmount a Locical Drive */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_mount ( |
BYTE drv, /* Logical drive number to be mounted/unmounted */ |
FATFS *fs /* Pointer to new file system object (NULL for unmount)*/ |
) |
{ |
if (drv >= _DRIVES) return FR_INVALID_DRIVE; |
if (FatFs[drv]) FatFs[drv]->fs_type = 0; /* Clear old object */ |
FatFs[drv] = fs; /* Register and clear new object */ |
if (fs) fs->fs_type = 0; |
return FR_OK; |
} |
/*-----------------------------------------------------------------------*/ |
/* Open or Create a File */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_open ( |
FIL *fp, /* Pointer to the blank file object */ |
const char *path, /* Pointer to the file name */ |
BYTE mode /* Access mode and file open mode flags */ |
) |
{ |
FRESULT res; |
DIR dj; |
BYTE *dir; |
char fn[8+3+1]; |
fp->fs = NULL; /* Clear file object */ |
#if !_FS_READONLY |
mode &= (FA_READ|FA_WRITE|FA_CREATE_ALWAYS|FA_OPEN_ALWAYS|FA_CREATE_NEW); |
res = auto_mount(&path, &dj.fs, (BYTE)(mode & (FA_WRITE|FA_CREATE_ALWAYS|FA_OPEN_ALWAYS|FA_CREATE_NEW))); |
#else |
mode &= FA_READ; |
res = auto_mount(&path, &dj.fs, 0); |
#endif |
if (res != FR_OK) return res; |
res = trace_path(&dj, fn, path, &dir); /* Trace the file path */ |
#if !_FS_READONLY |
/* Create or Open a file */ |
if (mode & (FA_CREATE_ALWAYS|FA_OPEN_ALWAYS|FA_CREATE_NEW)) { |
DWORD ps, rs; |
if (res != FR_OK) { /* No file, create new */ |
if (res != FR_NO_FILE) return res; |
res = reserve_direntry(&dj, &dir); |
if (res != FR_OK) return res; |
memset(dir, 0, 32); /* Initialize the new entry with open name */ |
memcpy(&dir[DIR_Name], fn, 8+3); |
dir[DIR_NTres] = fn[11]; |
mode |= FA_CREATE_ALWAYS; |
} |
else { /* Any object is already existing */ |
if (mode & FA_CREATE_NEW) /* Cannot create new */ |
return FR_EXIST; |
if (!dir || (dir[DIR_Attr] & (AM_RDO|AM_DIR))) /* Cannot overwrite it (R/O or DIR) */ |
return FR_DENIED; |
if (mode & FA_CREATE_ALWAYS) { /* Resize it to zero if needed */ |
rs = ((DWORD)LD_WORD(&dir[DIR_FstClusHI]) << 16) | LD_WORD(&dir[DIR_FstClusLO]); /* Get start cluster */ |
ST_WORD(&dir[DIR_FstClusHI], 0); /* cluster = 0 */ |
ST_WORD(&dir[DIR_FstClusLO], 0); |
ST_DWORD(&dir[DIR_FileSize], 0); /* size = 0 */ |
dj.fs->winflag = 1; |
ps = dj.fs->winsect; /* Remove the cluster chain */ |
if (!remove_chain(dj.fs, rs) || !move_window(dj.fs, ps)) |
return FR_RW_ERROR; |
dj.fs->last_clust = rs - 1; /* Reuse the cluster hole */ |
} |
} |
if (mode & FA_CREATE_ALWAYS) { |
dir[DIR_Attr] = 0; /* Reset attribute */ |
ps = get_fattime(); |
ST_DWORD(&dir[DIR_CrtTime], ps); /* Created time */ |
dj.fs->winflag = 1; |
mode |= FA__WRITTEN; /* Set file changed flag */ |
} |
} |
/* Open an existing file */ |
else { |
#endif /* !_FS_READONLY */ |
if (res != FR_OK) return res; /* Trace failed */ |
if (!dir || (dir[DIR_Attr] & AM_DIR)) /* It is a directory */ |
return FR_NO_FILE; |
#if !_FS_READONLY |
if ((mode & FA_WRITE) && (dir[DIR_Attr] & AM_RDO)) /* R/O violation */ |
return FR_DENIED; |
} |
fp->dir_sect = dj.fs->winsect; /* Pointer to the directory entry */ |
fp->dir_ptr = dir; |
#endif |
fp->flag = mode; /* File access mode */ |
fp->org_clust = /* File start cluster */ |
((DWORD)LD_WORD(&dir[DIR_FstClusHI]) << 16) | LD_WORD(&dir[DIR_FstClusLO]); |
fp->fsize = LD_DWORD(&dir[DIR_FileSize]); /* File size */ |
fp->fptr = 0; fp->csect = 255; /* File pointer */ |
fp->curr_sect = 0; |
fp->fs = dj.fs; fp->id = dj.fs->id; /* Owner file system object of the file */ |
return FR_OK; |
} |
/*-----------------------------------------------------------------------*/ |
/* Read File */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_read ( |
FIL *fp, /* Pointer to the file object */ |
void *buff, /* Pointer to data buffer */ |
UINT btr, /* Number of bytes to read */ |
UINT *br /* Pointer to number of bytes read */ |
) |
{ |
FRESULT res; |
DWORD clust, sect, remain; |
UINT rcnt, cc; |
BYTE *rbuff = buff; |
*br = 0; |
res = validate(fp->fs, fp->id); /* Check validity of the object */ |
if (res != FR_OK) return res; |
if (fp->flag & FA__ERROR) return FR_RW_ERROR; /* Check error flag */ |
if (!(fp->flag & FA_READ)) return FR_DENIED; /* Check access mode */ |
remain = fp->fsize - fp->fptr; |
if (btr > remain) btr = (UINT)remain; /* Truncate btr by remaining bytes */ |
for ( ; btr; /* Repeat until all data transferred */ |
rbuff += rcnt, fp->fptr += rcnt, *br += rcnt, btr -= rcnt) { |
if ((fp->fptr % SS(fp->fs)) == 0) { /* On the sector boundary? */ |
if (fp->csect >= fp->fs->csize) { /* On the cluster boundary? */ |
clust = (fp->fptr == 0) ? /* On the top of the file? */ |
fp->org_clust : get_cluster(fp->fs, fp->curr_clust); |
if (clust < 2 || clust >= fp->fs->max_clust) goto fr_error; |
fp->curr_clust = clust; /* Update current cluster */ |
fp->csect = 0; /* Reset sector address in the cluster */ |
} |
sect = clust2sect(fp->fs, fp->curr_clust) + fp->csect; /* Get current sector */ |
cc = btr / SS(fp->fs); /* When remaining bytes >= sector size, */ |
if (cc) { /* Read maximum contiguous sectors directly */ |
if (fp->csect + cc > fp->fs->csize) /* Clip at cluster boundary */ |
cc = fp->fs->csize - fp->csect; |
if (disk_read(fp->fs->drive, rbuff, sect, (BYTE)cc) != RES_OK) |
goto fr_error; |
fp->csect += (BYTE)cc; /* Next sector address in the cluster */ |
rcnt = SS(fp->fs) * cc; /* Number of bytes transferred */ |
continue; |
} |
if (sect != fp->curr_sect) { /* Is window offset changed? */ |
#if !_FS_READONLY |
if (fp->flag & FA__DIRTY) { /* Write back file I/O buffer if needed */ |
if (disk_write(fp->fs->drive, fp->buffer, fp->curr_sect, 1) != RES_OK) |
goto fr_error; |
fp->flag &= (BYTE)~FA__DIRTY; |
} |
#endif |
if (disk_read(fp->fs->drive, fp->buffer, sect, 1) != RES_OK) /* Fill file I/O buffer with file data */ |
goto fr_error; |
fp->curr_sect = sect; |
} |
fp->csect++; /* Next sector address in the cluster */ |
} |
rcnt = SS(fp->fs) - (fp->fptr % SS(fp->fs)); /* Get partial sector from file I/O buffer */ |
if (rcnt > btr) rcnt = btr; |
memcpy(rbuff, &fp->buffer[fp->fptr % SS(fp->fs)], rcnt); |
} |
return FR_OK; |
fr_error: /* Abort this file due to an unrecoverable error */ |
fp->flag |= FA__ERROR; |
return FR_RW_ERROR; |
} |
#if !_FS_READONLY |
/*-----------------------------------------------------------------------*/ |
/* Write File */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_write ( |
FIL *fp, /* Pointer to the file object */ |
const void *buff, /* Pointer to the data to be written */ |
UINT btw, /* Number of bytes to write */ |
UINT *bw /* Pointer to number of bytes written */ |
) |
{ |
FRESULT res; |
DWORD clust, sect; |
UINT wcnt, cc; |
const BYTE *wbuff = buff; |
*bw = 0; |
res = validate(fp->fs, fp->id); /* Check validity of the object */ |
if (res != FR_OK) return res; |
if (fp->flag & FA__ERROR) return FR_RW_ERROR; /* Check error flag */ |
if (!(fp->flag & FA_WRITE)) return FR_DENIED; /* Check access mode */ |
if (fp->fsize + btw < fp->fsize) return FR_OK; /* File size cannot reach 4GB */ |
for ( ; btw; /* Repeat until all data transferred */ |
wbuff += wcnt, fp->fptr += wcnt, *bw += wcnt, btw -= wcnt) { |
if ((fp->fptr % SS(fp->fs)) == 0) { /* On the sector boundary? */ |
if (fp->csect >= fp->fs->csize) { /* On the cluster boundary? */ |
if (fp->fptr == 0) { /* On the top of the file? */ |
clust = fp->org_clust; /* Follow from the origin */ |
if (clust == 0) /* When there is no cluster chain, */ |
fp->org_clust = clust = create_chain(fp->fs, 0); /* Create a new cluster chain */ |
} else { /* Middle or end of the file */ |
clust = create_chain(fp->fs, fp->curr_clust); /* Trace or streach cluster chain */ |
} |
if (clust == 0) break; /* Could not allocate a new cluster (disk full) */ |
if (clust == 1 || clust >= fp->fs->max_clust) goto fw_error; |
fp->curr_clust = clust; /* Update current cluster */ |
fp->csect = 0; /* Reset sector address in the cluster */ |
} |
sect = clust2sect(fp->fs, fp->curr_clust) + fp->csect; /* Get current sector */ |
cc = btw / SS(fp->fs); /* When remaining bytes >= sector size, */ |
if (cc) { /* Write maximum contiguous sectors directly */ |
if (fp->csect + cc > fp->fs->csize) /* Clip at cluster boundary */ |
cc = fp->fs->csize - fp->csect; |
if (disk_write(fp->fs->drive, wbuff, sect, (BYTE)cc) != RES_OK) |
goto fw_error; |
fp->csect += (BYTE)cc; /* Next sector address in the cluster */ |
wcnt = SS(fp->fs) * cc; /* Number of bytes transferred */ |
continue; |
} |
if (sect != fp->curr_sect) { /* Is window offset changed? */ |
if (fp->flag & FA__DIRTY) { /* Write back file I/O buffer if needed */ |
if (disk_write(fp->fs->drive, fp->buffer, fp->curr_sect, 1) != RES_OK) |
goto fw_error; |
fp->flag &= (BYTE)~FA__DIRTY; |
} |
if (fp->fptr < fp->fsize && /* Fill file I/O buffer with file data */ |
disk_read(fp->fs->drive, fp->buffer, sect, 1) != RES_OK) |
goto fw_error; |
fp->curr_sect = sect; |
} |
fp->csect++; /* Next sector address in the cluster */ |
} |
wcnt = SS(fp->fs) - (fp->fptr % SS(fp->fs)); /* Put partial sector into file I/O buffer */ |
if (wcnt > btw) wcnt = btw; |
memcpy(&fp->buffer[fp->fptr % SS(fp->fs)], wbuff, wcnt); |
fp->flag |= FA__DIRTY; |
} |
if (fp->fptr > fp->fsize) fp->fsize = fp->fptr; /* Update file size if needed */ |
fp->flag |= FA__WRITTEN; /* Set file changed flag */ |
return FR_OK; |
fw_error: /* Abort this file due to an unrecoverable error */ |
fp->flag |= FA__ERROR; |
return FR_RW_ERROR; |
} |
/*-----------------------------------------------------------------------*/ |
/* Synchronize the file object */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_sync ( |
FIL *fp /* Pointer to the file object */ |
) |
{ |
FRESULT res; |
DWORD tim; |
BYTE *dir; |
res = validate(fp->fs, fp->id); /* Check validity of the object */ |
if (res == FR_OK) { |
if (fp->flag & FA__WRITTEN) { /* Has the file been written? */ |
/* Write back data buffer if needed */ |
if (fp->flag & FA__DIRTY) { |
if (disk_write(fp->fs->drive, fp->buffer, fp->curr_sect, 1) != RES_OK) |
return FR_RW_ERROR; |
fp->flag &= (BYTE)~FA__DIRTY; |
} |
/* Update the directory entry */ |
if (!move_window(fp->fs, fp->dir_sect)) |
return FR_RW_ERROR; |
dir = fp->dir_ptr; |
dir[DIR_Attr] |= AM_ARC; /* Set archive bit */ |
ST_DWORD(&dir[DIR_FileSize], fp->fsize); /* Update file size */ |
ST_WORD(&dir[DIR_FstClusLO], fp->org_clust); /* Update start cluster */ |
ST_WORD(&dir[DIR_FstClusHI], fp->org_clust >> 16); |
tim = get_fattime(); /* Updated time */ |
ST_DWORD(&dir[DIR_WrtTime], tim); |
fp->flag &= (BYTE)~FA__WRITTEN; |
res = sync(fp->fs); |
} |
} |
return res; |
} |
#endif /* !_FS_READONLY */ |
/*-----------------------------------------------------------------------*/ |
/* Close File */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_close ( |
FIL *fp /* Pointer to the file object to be closed */ |
) |
{ |
FRESULT res; |
#if !_FS_READONLY |
res = f_sync(fp); |
#else |
res = validate(fp->fs, fp->id); |
#endif |
if (res == FR_OK) fp->fs = NULL; |
return res; |
} |
#if _FS_MINIMIZE <= 2 |
/*-----------------------------------------------------------------------*/ |
/* Seek File R/W Pointer */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_lseek ( |
FIL *fp, /* Pointer to the file object */ |
DWORD ofs /* File pointer from top of file */ |
) |
{ |
FRESULT res; |
DWORD clust, csize, nsect, ifptr; |
res = validate(fp->fs, fp->id); /* Check validity of the object */ |
if (res != FR_OK) return res; |
if (fp->flag & FA__ERROR) return FR_RW_ERROR; |
if (ofs > fp->fsize /* In read-only mode, clip offset with the file size */ |
#if !_FS_READONLY |
&& !(fp->flag & FA_WRITE) |
#endif |
) ofs = fp->fsize; |
ifptr = fp->fptr; |
fp->fptr = 0; fp->csect = 255; |
nsect = 0; |
if (ofs > 0) { |
csize = (DWORD)fp->fs->csize * SS(fp->fs); /* Cluster size (byte) */ |
if (ifptr > 0 && |
(ofs - 1) / csize >= (ifptr - 1) / csize) {/* When seek to same or following cluster, */ |
fp->fptr = (ifptr - 1) & ~(csize - 1); /* start from the current cluster */ |
ofs -= fp->fptr; |
clust = fp->curr_clust; |
} else { /* When seek to back cluster, */ |
clust = fp->org_clust; /* start from the first cluster */ |
#if !_FS_READONLY |
if (clust == 0) { /* If no cluster chain, create a new chain */ |
clust = create_chain(fp->fs, 0); |
if (clust == 1) goto fk_error; |
fp->org_clust = clust; |
} |
#endif |
fp->curr_clust = clust; |
} |
if (clust != 0) { |
while (ofs > csize) { /* Cluster following loop */ |
#if !_FS_READONLY |
if (fp->flag & FA_WRITE) { /* Check if in write mode or not */ |
clust = create_chain(fp->fs, clust); /* Force streached if in write mode */ |
if (clust == 0) { /* When disk gets full, clip file size */ |
ofs = csize; break; |
} |
} else |
#endif |
clust = get_cluster(fp->fs, clust); /* Follow cluster chain if not in write mode */ |
if (clust < 2 || clust >= fp->fs->max_clust) goto fk_error; |
fp->curr_clust = clust; |
fp->fptr += csize; |
ofs -= csize; |
} |
fp->fptr += ofs; |
fp->csect = (BYTE)(ofs / SS(fp->fs)); /* Sector offset in the cluster */ |
if (ofs & (SS(fp->fs) - 1)) { |
nsect = clust2sect(fp->fs, clust) + fp->csect; /* Current sector */ |
fp->csect++; |
} |
} |
} |
if (nsect && nsect != fp->curr_sect) { |
#if !_FS_READONLY |
if (fp->flag & FA__DIRTY) { /* Write-back dirty buffer if needed */ |
if (disk_write(fp->fs->drive, fp->buffer, fp->curr_sect, 1) != RES_OK) |
goto fk_error; |
fp->flag &= (BYTE)~FA__DIRTY; |
} |
#endif |
if (disk_read(fp->fs->drive, fp->buffer, nsect, 1) != RES_OK) |
goto fk_error; |
fp->curr_sect = nsect; |
} |
#if !_FS_READONLY |
if (fp->fptr > fp->fsize) { /* Set changed flag if the file was extended */ |
fp->fsize = fp->fptr; |
fp->flag |= FA__WRITTEN; |
} |
#endif |
return FR_OK; |
fk_error: /* Abort this file due to an unrecoverable error */ |
fp->flag |= FA__ERROR; |
return FR_RW_ERROR; |
} |
#if _FS_MINIMIZE <= 1 |
/*-----------------------------------------------------------------------*/ |
/* Create a directroy object */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_opendir ( |
DIR *dj, /* Pointer to directory object to create */ |
const char *path /* Pointer to the directory path */ |
) |
{ |
FRESULT res; |
BYTE *dir; |
char fn[8+3+1]; |
res = auto_mount(&path, &dj->fs, 0); |
if (res == FR_OK) { |
res = trace_path(dj, fn, path, &dir); /* Trace the directory path */ |
if (res == FR_OK) { /* Trace completed */ |
if (dir) { /* It is not the root dir */ |
if (dir[DIR_Attr] & AM_DIR) { /* The entry is a directory */ |
dj->clust = ((DWORD)LD_WORD(&dir[DIR_FstClusHI]) << 16) | LD_WORD(&dir[DIR_FstClusLO]); |
dj->sect = clust2sect(dj->fs, dj->clust); |
dj->index = 2; |
} else { /* The entry is not a directory */ |
res = FR_NO_FILE; |
} |
} |
dj->id = dj->fs->id; |
} |
} |
return res; |
} |
/*-----------------------------------------------------------------------*/ |
/* Read Directory Entry in Sequense */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_readdir ( |
DIR *dj, /* Pointer to the directory object */ |
FILINFO *finfo /* Pointer to file information to return */ |
) |
{ |
BYTE *dir, c, res; |
res = validate(dj->fs, dj->id); /* Check validity of the object */ |
if (res != FR_OK) return res; |
finfo->fname[0] = 0; |
while (dj->sect) { |
if (!move_window(dj->fs, dj->sect)) |
return FR_RW_ERROR; |
dir = &dj->fs->win[(dj->index & ((SS(dj->fs) - 1) >> 5)) * 32]; /* pointer to the directory entry */ |
c = dir[DIR_Name]; |
if (c == 0) break; /* Has it reached to end of dir? */ |
if (c != 0xE5 && !(dir[DIR_Attr] & AM_VOL)) /* Is it a valid entry? */ |
get_fileinfo(finfo, dir); |
if (!next_dir_entry(dj)) dj->sect = 0; /* Next entry */ |
if (finfo->fname[0]) break; /* Found valid entry */ |
} |
return FR_OK; |
} |
#if _FS_MINIMIZE == 0 |
/*-----------------------------------------------------------------------*/ |
/* Get File Status */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_stat ( |
const char *path, /* Pointer to the file path */ |
FILINFO *finfo /* Pointer to file information to return */ |
) |
{ |
FRESULT res; |
DIR dj; |
BYTE *dir; |
char fn[8+3+1]; |
res = auto_mount(&path, &dj.fs, 0); |
if (res == FR_OK) { |
res = trace_path(&dj, fn, path, &dir); /* Trace the file path */ |
if (res == FR_OK) { /* Trace completed */ |
if (dir) /* Found an object */ |
get_fileinfo(finfo, dir); |
else /* It is root dir */ |
res = FR_INVALID_NAME; |
} |
} |
return res; |
} |
#if !_FS_READONLY |
/*-----------------------------------------------------------------------*/ |
/* Truncate File */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_truncate ( |
FIL *fp /* Pointer to the file object */ |
) |
{ |
FRESULT res; |
DWORD ncl; |
res = validate(fp->fs, fp->id); /* Check validity of the object */ |
if (res != FR_OK) return res; |
if (fp->flag & FA__ERROR) return FR_RW_ERROR; /* Check error flag */ |
if (!(fp->flag & FA_WRITE)) return FR_DENIED; /* Check access mode */ |
if (fp->fsize > fp->fptr) { |
fp->fsize = fp->fptr; /* Set file size to current R/W point */ |
fp->flag |= FA__WRITTEN; |
if (fp->fptr == 0) { /* When set file size to zero, remove entire cluster chain */ |
if (!remove_chain(fp->fs, fp->org_clust)) goto ft_error; |
fp->org_clust = 0; |
} else { /* When truncate a part of the file, remove remaining clusters */ |
ncl = get_cluster(fp->fs, fp->curr_clust); |
if (ncl < 2) goto ft_error; |
if (ncl < fp->fs->max_clust) { |
if (!put_cluster(fp->fs, fp->curr_clust, 0x0FFFFFFF)) goto ft_error; |
if (!remove_chain(fp->fs, ncl)) goto ft_error; |
} |
} |
} |
return FR_OK; |
ft_error: /* Abort this file due to an unrecoverable error */ |
fp->flag |= FA__ERROR; |
return FR_RW_ERROR; |
} |
/*-----------------------------------------------------------------------*/ |
/* Get Number of Free Clusters */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_getfree ( |
const char *drv, /* Pointer to the logical drive number (root dir) */ |
DWORD *nclust, /* Pointer to the variable to return number of free clusters */ |
FATFS **fatfs /* Pointer to pointer to corresponding file system object to return */ |
) |
{ |
FRESULT res; |
DWORD n, clust, sect; |
BYTE fat, f, *p; |
/* Get drive number */ |
res = auto_mount(&drv, fatfs, 0); |
if (res != FR_OK) return res; |
/* If number of free cluster is valid, return it without cluster scan. */ |
if ((*fatfs)->free_clust <= (*fatfs)->max_clust - 2) { |
*nclust = (*fatfs)->free_clust; |
return FR_OK; |
} |
/* Get number of free clusters */ |
fat = (*fatfs)->fs_type; |
n = 0; |
if (fat == FS_FAT12) { |
clust = 2; |
do { |
if ((WORD)get_cluster(*fatfs, clust) == 0) n++; |
} while (++clust < (*fatfs)->max_clust); |
} else { |
clust = (*fatfs)->max_clust; |
sect = (*fatfs)->fatbase; |
f = 0; p = 0; |
do { |
if (!f) { |
if (!move_window(*fatfs, sect++)) return FR_RW_ERROR; |
p = (*fatfs)->win; |
} |
if (fat == FS_FAT16) { |
if (LD_WORD(p) == 0) n++; |
p += 2; f += 1; |
} else { |
if (LD_DWORD(p) == 0) n++; |
p += 4; f += 2; |
} |
} while (--clust); |
} |
(*fatfs)->free_clust = n; |
#if _USE_FSINFO |
if (fat == FS_FAT32) (*fatfs)->fsi_flag = 1; |
#endif |
*nclust = n; |
return FR_OK; |
} |
/*-----------------------------------------------------------------------*/ |
/* Delete a File or Directory */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_unlink ( |
const char *path /* Pointer to the file or directory path */ |
) |
{ |
FRESULT res; |
DIR dj; |
BYTE *dir, *sdir; |
DWORD dclust, dsect; |
char fn[8+3+1]; |
res = auto_mount(&path, &dj.fs, 1); |
if (res != FR_OK) return res; |
res = trace_path(&dj, fn, path, &dir); /* Trace the file path */ |
if (res != FR_OK) return res; /* Trace failed */ |
if (!dir) return FR_INVALID_NAME; /* It is the root directory */ |
if (dir[DIR_Attr] & AM_RDO) return FR_DENIED; /* It is a R/O object */ |
dsect = dj.fs->winsect; |
dclust = ((DWORD)LD_WORD(&dir[DIR_FstClusHI]) << 16) | LD_WORD(&dir[DIR_FstClusLO]); |
if (dir[DIR_Attr] & AM_DIR) { /* It is a sub-directory */ |
dj.clust = dclust; /* Check if the sub-dir is empty or not */ |
dj.sect = clust2sect(dj.fs, dclust); |
dj.index = 2; |
do { |
if (!move_window(dj.fs, dj.sect)) return FR_RW_ERROR; |
sdir = &dj.fs->win[(dj.index & ((SS(dj.fs) - 1) >> 5)) * 32]; |
if (sdir[DIR_Name] == 0) break; |
if (sdir[DIR_Name] != 0xE5 && !(sdir[DIR_Attr] & AM_VOL)) |
return FR_DENIED; /* The directory is not empty */ |
} while (next_dir_entry(&dj)); |
} |
if (!move_window(dj.fs, dsect)) return FR_RW_ERROR; /* Mark the directory entry 'deleted' */ |
dir[DIR_Name] = 0xE5; |
dj.fs->winflag = 1; |
if (!remove_chain(dj.fs, dclust)) return FR_RW_ERROR; /* Remove the cluster chain */ |
return sync(dj.fs); |
} |
/*-----------------------------------------------------------------------*/ |
/* Create a Directory */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_mkdir ( |
const char *path /* Pointer to the directory path */ |
) |
{ |
FRESULT res; |
DIR dj; |
BYTE *dir, *fw, n; |
char fn[8+3+1]; |
DWORD sect, dsect, dclust, pclust, tim; |
res = auto_mount(&path, &dj.fs, 1); |
if (res != FR_OK) return res; |
res = trace_path(&dj, fn, path, &dir); /* Trace the file path */ |
if (res == FR_OK) return FR_EXIST; /* Any file or directory is already existing */ |
if (res != FR_NO_FILE) return res; |
res = reserve_direntry(&dj, &dir); /* Reserve a directory entry */ |
if (res != FR_OK) return res; |
sect = dj.fs->winsect; |
dclust = create_chain(dj.fs, 0); /* Allocate a cluster for new directory table */ |
if (dclust == 1) return FR_RW_ERROR; |
dsect = clust2sect(dj.fs, dclust); |
if (!dsect) return FR_DENIED; |
if (!move_window(dj.fs, dsect)) return FR_RW_ERROR; |
fw = dj.fs->win; |
memset(fw, 0, SS(dj.fs)); /* Clear the new directory table */ |
for (n = 1; n < dj.fs->csize; n++) { |
if (disk_write(dj.fs->drive, fw, ++dsect, 1) != RES_OK) |
return FR_RW_ERROR; |
} |
memset(&fw[DIR_Name], ' ', 8+3); /* Create "." entry */ |
fw[DIR_Name] = '.'; |
fw[DIR_Attr] = AM_DIR; |
tim = get_fattime(); |
ST_DWORD(&fw[DIR_WrtTime], tim); |
memcpy(&fw[32], &fw[0], 32); fw[33] = '.'; /* Create ".." entry */ |
ST_WORD(&fw[ DIR_FstClusLO], dclust); |
ST_WORD(&fw[ DIR_FstClusHI], dclust >> 16); |
pclust = dj.sclust; |
if (dj.fs->fs_type == FS_FAT32 && pclust == dj.fs->dirbase) pclust = 0; |
ST_WORD(&fw[32+DIR_FstClusLO], pclust); |
ST_WORD(&fw[32+DIR_FstClusHI], pclust >> 16); |
dj.fs->winflag = 1; |
if (!move_window(dj.fs, sect)) return FR_RW_ERROR; |
memset(&dir[0], 0, 32); /* Initialize the new entry */ |
memcpy(&dir[DIR_Name], fn, 8+3); /* Name */ |
dir[DIR_NTres] = fn[11]; |
dir[DIR_Attr] = AM_DIR; /* Attribute */ |
ST_DWORD(&dir[DIR_WrtTime], tim); /* Crated time */ |
ST_WORD(&dir[DIR_FstClusLO], dclust); /* Table start cluster */ |
ST_WORD(&dir[DIR_FstClusHI], dclust >> 16); |
return sync(dj.fs); |
} |
/*-----------------------------------------------------------------------*/ |
/* Change File Attribute */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_chmod ( |
const char *path, /* Pointer to the file path */ |
BYTE value, /* Attribute bits */ |
BYTE mask /* Attribute mask to change */ |
) |
{ |
FRESULT res; |
DIR dj; |
BYTE *dir; |
char fn[8+3+1]; |
res = auto_mount(&path, &dj.fs, 1); |
if (res == FR_OK) { |
res = trace_path(&dj, fn, path, &dir); /* Trace the file path */ |
if (res == FR_OK) { /* Trace completed */ |
if (!dir) { |
res = FR_INVALID_NAME; /* Root directory */ |
} else { |
mask &= AM_RDO|AM_HID|AM_SYS|AM_ARC; /* Valid attribute mask */ |
dir[DIR_Attr] = (value & mask) | (dir[DIR_Attr] & (BYTE)~mask); /* Apply attribute change */ |
res = sync(dj.fs); |
} |
} |
} |
return res; |
} |
/*-----------------------------------------------------------------------*/ |
/* Change Timestamp */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_utime ( |
const char *path, /* Pointer to the file/directory name */ |
const FILINFO *finfo /* Pointer to the timestamp to be set */ |
) |
{ |
FRESULT res; |
DIR dj; |
BYTE *dir; |
char fn[8+3+1]; |
res = auto_mount(&path, &dj.fs, 1); |
if (res == FR_OK) { |
res = trace_path(&dj, fn, path, &dir); /* Trace the file path */ |
if (res == FR_OK) { /* Trace completed */ |
if (!dir) { |
res = FR_INVALID_NAME; /* Root directory */ |
} else { |
ST_WORD(&dir[DIR_WrtTime], finfo->ftime); |
ST_WORD(&dir[DIR_WrtDate], finfo->fdate); |
res = sync(dj.fs); |
} |
} |
} |
return res; |
} |
/*-----------------------------------------------------------------------*/ |
/* Rename File/Directory */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_rename ( |
const char *path_old, /* Pointer to the old name */ |
const char *path_new /* Pointer to the new name */ |
) |
{ |
FRESULT res; |
DIR dj; |
DWORD sect_old; |
BYTE *dir_old, *dir_new, direntry[32-11]; |
char fn[8+3+1]; |
res = auto_mount(&path_old, &dj.fs, 1); |
if (res != FR_OK) return res; |
res = trace_path(&dj, fn, path_old, &dir_old); /* Check old object */ |
if (res != FR_OK) return res; /* The old object is not found */ |
if (!dir_old) return FR_NO_FILE; |
sect_old = dj.fs->winsect; /* Save the object information */ |
memcpy(direntry, &dir_old[DIR_Attr], 32-11); |
res = trace_path(&dj, fn, path_new, &dir_new); /* Check new object */ |
if (res == FR_OK) return FR_EXIST; /* The new object name is already existing */ |
if (res != FR_NO_FILE) return res; /* Is there no old name? */ |
res = reserve_direntry(&dj, &dir_new); /* Reserve a directory entry */ |
if (res != FR_OK) return res; |
memcpy(&dir_new[DIR_Attr], direntry, 32-11); /* Create new entry */ |
memcpy(&dir_new[DIR_Name], fn, 8+3); |
dir_new[DIR_NTres] = fn[11]; |
dj.fs->winflag = 1; |
if (!move_window(dj.fs, sect_old)) return FR_RW_ERROR; /* Delete old entry */ |
dir_old[DIR_Name] = 0xE5; |
return sync(dj.fs); |
} |
#endif /* !_FS_READONLY */ |
#endif /* _FS_MINIMIZE == 0 */ |
#endif /* _FS_MINIMIZE <= 1 */ |
#endif /* _FS_MINIMIZE <= 2 */ |
#if _USE_MKFS && !_FS_READONLY |
/*-----------------------------------------------------------------------*/ |
/* Create File System on the Drive */ |
/*-----------------------------------------------------------------------*/ |
#define N_ROOTDIR 512 /* Multiple of 32 and <= 2048 */ |
#define N_FATS 1 /* 1 or 2 */ |
#define MAX_SECTOR 64000000UL /* Maximum partition size */ |
#define MIN_SECTOR 2000UL /* Minimum partition size */ |
FRESULT f_mkfs ( |
BYTE drv, /* Logical drive number */ |
BYTE partition, /* Partitioning rule 0:FDISK, 1:SFD */ |
WORD allocsize /* Allocation unit size [bytes] */ |
) |
{ |
BYTE fmt, m, *tbl; |
DWORD b_part, b_fat, b_dir, b_data; /* Area offset (LBA) */ |
DWORD n_part, n_rsv, n_fat, n_dir; /* Area size */ |
DWORD n_clust, n; |
FATFS *fs; |
DSTATUS stat; |
/* Check validity of the parameters */ |
if (drv >= _DRIVES) return FR_INVALID_DRIVE; |
if (partition >= 2) return FR_MKFS_ABORTED; |
for (n = 512; n <= 32768U && n != allocsize; n <<= 1); |
if (n != allocsize) return FR_MKFS_ABORTED; |
/* Check mounted drive and clear work area */ |
fs = FatFs[drv]; |
if (!fs) return FR_NOT_ENABLED; |
fs->fs_type = 0; |
drv = LD2PD(drv); |
/* Get disk statics */ |
stat = disk_initialize(drv); |
if (stat & STA_NOINIT) return FR_NOT_READY; |
if (stat & STA_PROTECT) return FR_WRITE_PROTECTED; |
if (disk_ioctl(drv, GET_SECTOR_COUNT, &n_part) != RES_OK || n_part < MIN_SECTOR) |
return FR_MKFS_ABORTED; |
if (n_part > MAX_SECTOR) n_part = MAX_SECTOR; |
b_part = (!partition) ? 63 : 0; /* Boot sector */ |
n_part -= b_part; |
#if S_MAX_SIZ > 512 /* Check disk sector size */ |
if (disk_ioctl(drv, GET_SECTOR_SIZE, &SS(fs)) != RES_OK |
|| SS(fs) > S_MAX_SIZ |
|| SS(fs) > allocsize) |
return FR_MKFS_ABORTED; |
#endif |
allocsize /= SS(fs); /* Number of sectors per cluster */ |
/* Pre-compute number of clusters and FAT type */ |
n_clust = n_part / allocsize; |
fmt = FS_FAT12; |
if (n_clust >= 0xFF5) fmt = FS_FAT16; |
if (n_clust >= 0xFFF5) fmt = FS_FAT32; |
/* Determine offset and size of FAT structure */ |
switch (fmt) { |
case FS_FAT12: |
n_fat = ((n_clust * 3 + 1) / 2 + 3 + SS(fs) - 1) / SS(fs); |
n_rsv = 1 + partition; |
n_dir = N_ROOTDIR * 32 / SS(fs); |
break; |
case FS_FAT16: |
n_fat = ((n_clust * 2) + 4 + SS(fs) - 1) / SS(fs); |
n_rsv = 1 + partition; |
n_dir = N_ROOTDIR * 32 / SS(fs); |
break; |
default: |
n_fat = ((n_clust * 4) + 8 + SS(fs) - 1) / SS(fs); |
n_rsv = 33 - partition; |
n_dir = 0; |
} |
b_fat = b_part + n_rsv; /* FATs start sector */ |
b_dir = b_fat + n_fat * N_FATS; /* Directory start sector */ |
b_data = b_dir + n_dir; /* Data start sector */ |
/* Align data start sector to erase block boundary (for flash memory media) */ |
if (disk_ioctl(drv, GET_BLOCK_SIZE, &n) != RES_OK) return FR_MKFS_ABORTED; |
n = (b_data + n - 1) & ~(n - 1); |
n_fat += (n - b_data) / N_FATS; |
/* b_dir and b_data are no longer used below */ |
/* Determine number of cluster and final check of validity of the FAT type */ |
n_clust = (n_part - n_rsv - n_fat * N_FATS - n_dir) / allocsize; |
if ( (fmt == FS_FAT16 && n_clust < 0xFF5) |
|| (fmt == FS_FAT32 && n_clust < 0xFFF5)) |
return FR_MKFS_ABORTED; |
/* Create partition table if needed */ |
if (!partition) { |
DWORD n_disk = b_part + n_part; |
tbl = &fs->win[MBR_Table]; |
ST_DWORD(&tbl[0], 0x00010180); /* Partition start in CHS */ |
if (n_disk < 63UL * 255 * 1024) { /* Partition end in CHS */ |
n_disk = n_disk / 63 / 255; |
tbl[7] = (BYTE)n_disk; |
tbl[6] = (BYTE)((n_disk >> 2) | 63); |
} else { |
ST_WORD(&tbl[6], 0xFFFF); |
} |
tbl[5] = 254; |
if (fmt != FS_FAT32) /* System ID */ |
tbl[4] = (n_part < 0x10000) ? 0x04 : 0x06; |
else |
tbl[4] = 0x0c; |
ST_DWORD(&tbl[8], 63); /* Partition start in LBA */ |
ST_DWORD(&tbl[12], n_part); /* Partition size in LBA */ |
ST_WORD(&tbl[64], 0xAA55); /* Signature */ |
if (disk_write(drv, fs->win, 0, 1) != RES_OK) |
return FR_RW_ERROR; |
} |
/* Create boot record */ |
tbl = fs->win; /* Clear buffer */ |
memset(tbl, 0, SS(fs)); |
ST_DWORD(&tbl[BS_jmpBoot], 0x90FEEB); /* Boot code (jmp $, nop) */ |
ST_WORD(&tbl[BPB_BytsPerSec], SS(fs)); /* Sector size */ |
tbl[BPB_SecPerClus] = (BYTE)allocsize; /* Sectors per cluster */ |
ST_WORD(&tbl[BPB_RsvdSecCnt], n_rsv); /* Reserved sectors */ |
tbl[BPB_NumFATs] = N_FATS; /* Number of FATs */ |
ST_WORD(&tbl[BPB_RootEntCnt], SS(fs) / 32 * n_dir); /* Number of rootdir entries */ |
if (n_part < 0x10000) { /* Number of total sectors */ |
ST_WORD(&tbl[BPB_TotSec16], n_part); |
} else { |
ST_DWORD(&tbl[BPB_TotSec32], n_part); |
} |
tbl[BPB_Media] = 0xF8; /* Media descripter */ |
ST_WORD(&tbl[BPB_SecPerTrk], 63); /* Number of sectors per track */ |
ST_WORD(&tbl[BPB_NumHeads], 255); /* Number of heads */ |
ST_DWORD(&tbl[BPB_HiddSec], b_part); /* Hidden sectors */ |
n = get_fattime(); /* Use current time as a VSN */ |
if (fmt != FS_FAT32) { |
ST_DWORD(&tbl[BS_VolID], n); /* Volume serial number */ |
ST_WORD(&tbl[BPB_FATSz16], n_fat); /* Number of secters per FAT */ |
tbl[BS_DrvNum] = 0x80; /* Drive number */ |
tbl[BS_BootSig] = 0x29; /* Extended boot signature */ |
memcpy(&tbl[BS_VolLab], "NO NAME FAT ", 19); /* Volume lavel, FAT signature */ |
} else { |
ST_DWORD(&tbl[BS_VolID32], n); /* Volume serial number */ |
ST_DWORD(&tbl[BPB_FATSz32], n_fat); /* Number of secters per FAT */ |
ST_DWORD(&tbl[BPB_RootClus], 2); /* Root directory cluster (2) */ |
ST_WORD(&tbl[BPB_FSInfo], 1); /* FSInfo record (bs+1) */ |
ST_WORD(&tbl[BPB_BkBootSec], 6); /* Backup boot record (bs+6) */ |
tbl[BS_DrvNum32] = 0x80; /* Drive number */ |
tbl[BS_BootSig32] = 0x29; /* Extended boot signature */ |
memcpy(&tbl[BS_VolLab32], "NO NAME FAT32 ", 19); /* Volume lavel, FAT signature */ |
} |
ST_WORD(&tbl[BS_55AA], 0xAA55); /* Signature */ |
if (disk_write(drv, tbl, b_part+0, 1) != RES_OK) |
return FR_RW_ERROR; |
if (fmt == FS_FAT32) |
disk_write(drv, tbl, b_part+6, 1); |
/* Initialize FAT area */ |
for (m = 0; m < N_FATS; m++) { |
memset(tbl, 0, SS(fs)); /* 1st sector of the FAT */ |
if (fmt != FS_FAT32) { |
n = (fmt == FS_FAT12) ? 0x00FFFFF8 : 0xFFFFFFF8; |
ST_DWORD(&tbl[0], n); /* Reserve cluster #0-1 (FAT12/16) */ |
} else { |
ST_DWORD(&tbl[0], 0xFFFFFFF8); /* Reserve cluster #0-1 (FAT32) */ |
ST_DWORD(&tbl[4], 0xFFFFFFFF); |
ST_DWORD(&tbl[8], 0x0FFFFFFF); /* Reserve cluster #2 for root dir */ |
} |
if (disk_write(drv, tbl, b_fat++, 1) != RES_OK) |
return FR_RW_ERROR; |
memset(tbl, 0, SS(fs)); /* Following FAT entries are filled by zero */ |
for (n = 1; n < n_fat; n++) { |
if (disk_write(drv, tbl, b_fat++, 1) != RES_OK) |
return FR_RW_ERROR; |
} |
} |
/* Initialize Root directory */ |
m = (BYTE)((fmt == FS_FAT32) ? allocsize : n_dir); |
do { |
if (disk_write(drv, tbl, b_fat++, 1) != RES_OK) |
return FR_RW_ERROR; |
} while (--m); |
/* Create FSInfo record if needed */ |
if (fmt == FS_FAT32) { |
ST_WORD(&tbl[BS_55AA], 0xAA55); |
ST_DWORD(&tbl[FSI_LeadSig], 0x41615252); |
ST_DWORD(&tbl[FSI_StrucSig], 0x61417272); |
ST_DWORD(&tbl[FSI_Free_Count], n_clust - 1); |
ST_DWORD(&tbl[FSI_Nxt_Free], 0xFFFFFFFF); |
disk_write(drv, tbl, b_part+1, 1); |
disk_write(drv, tbl, b_part+7, 1); |
} |
return (disk_ioctl(drv, CTRL_SYNC, NULL) == RES_OK) ? FR_OK : FR_RW_ERROR; |
} |
#endif /* _USE_MKFS && !_FS_READONLY */ |
#if _USE_STRFUNC >= 1 |
/*-----------------------------------------------------------------------*/ |
/* Get a string from the file */ |
/*-----------------------------------------------------------------------*/ |
char* fgets ( |
char* buff, /* Pointer to the string buffer to read */ |
int len, /* Size of string buffer */ |
FIL* fil /* Pointer to the file object */ |
) |
{ |
int i = 0; |
char *p = buff; |
UINT rc; |
while (i < len - 1) { /* Read bytes until buffer gets filled */ |
f_read(fil, p, 1, &rc); |
if (rc != 1) break; /* Break when no data to read */ |
#if _USE_STRFUNC >= 2 |
if (*p == '\r') continue; /* Strip '\r' */ |
#endif |
i++; |
if (*p++ == '\n') break; /* Break when reached end of line */ |
} |
*p = 0; |
return i ? buff : 0; /* When no data read (eof or error), return with error. */ |
} |
#if !_FS_READONLY |
#include <stdarg.h> |
/*-----------------------------------------------------------------------*/ |
/* Put a character to the file */ |
/*-----------------------------------------------------------------------*/ |
int fputc ( |
int chr, /* A character to be output */ |
FIL* fil /* Ponter to the file object */ |
) |
{ |
UINT bw; |
char c; |
#if _USE_STRFUNC >= 2 |
if (chr == '\n') fputc ('\r', fil); /* LF -> CRLF conversion */ |
#endif |
if (!fil) { /* Special value may be used to switch the destination to any other device */ |
/* put_console(chr); */ |
return chr; |
} |
c = (char)chr; |
f_write(fil, &c, 1, &bw); /* Write a byte to the file */ |
return bw ? chr : EOF; /* Return the resulut */ |
} |
/*-----------------------------------------------------------------------*/ |
/* Put a string to the file */ |
/*-----------------------------------------------------------------------*/ |
int fputs ( |
const char* str, /* Pointer to the string to be output */ |
FIL* fil /* Pointer to the file object */ |
) |
{ |
int n; |
for (n = 0; *str; str++, n++) { |
if (fputc(*str, fil) == EOF) return EOF; |
} |
return n; |
} |
/*-----------------------------------------------------------------------*/ |
/* Put a formatted string to the file */ |
/*-----------------------------------------------------------------------*/ |
int fprintf ( |
FIL* fil, /* Pointer to the file object */ |
const char* str, /* Pointer to the format string */ |
... /* Optional arguments... */ |
) |
{ |
va_list arp; |
UCHAR c, f, r; |
ULONG val; |
char s[16]; |
int i, w, res, cc; |
va_start(arp, str); |
for (cc = res = 0; cc != EOF; res += cc) { |
c = *str++; |
if (c == 0) break; /* End of string */ |
if (c != '%') { /* Non escape cahracter */ |
cc = fputc(c, fil); |
if (cc != EOF) cc = 1; |
continue; |
} |
w = f = 0; |
c = *str++; |
if (c == '0') { /* Flag: '0' padding */ |
f = 1; c = *str++; |
} |
while (c >= '0' && c <= '9') { /* Precision */ |
w = w * 10 + (c - '0'); |
c = *str++; |
} |
if (c == 'l') { /* Prefix: Size is long int */ |
f |= 2; c = *str++; |
} |
if (c == 's') { /* Type is string */ |
cc = fputs(va_arg(arp, char*), fil); |
continue; |
} |
if (c == 'c') { /* Type is character */ |
cc = fputc(va_arg(arp, char), fil); |
if (cc != EOF) cc = 1; |
continue; |
} |
r = 0; |
if (c == 'd') r = 10; /* Type is signed decimal */ |
if (c == 'u') r = 10; /* Type is unsigned decimal */ |
if (c == 'X') r = 16; /* Type is unsigned hexdecimal */ |
if (r == 0) break; /* Unknown type */ |
if (f & 2) { /* Get the value */ |
val = (ULONG)va_arg(arp, long); |
} else { |
val = (c == 'd') ? (ULONG)(long)va_arg(arp, int) : (ULONG)va_arg(arp, unsigned int); |
} |
/* Put numeral string */ |
if (c == 'd') { |
if (val >= 0x80000000) { |
val = 0 - val; |
f |= 4; |
} |
} |
i = sizeof(s) - 1; s[i] = 0; |
do { |
c = (UCHAR)(val % r + '0'); |
if (c > '9') c += 7; |
s[--i] = c; |
val /= r; |
} while (i && val); |
if (i && (f & 4)) s[--i] = '-'; |
w = sizeof(s) - 1 - w; |
while (i && i > w) s[--i] = (f & 1) ? '0' : ' '; |
cc = fputs(&s[i], fil); |
} |
va_end(arp); |
return (cc == EOF) ? cc : res; |
} |
#endif /* !_FS_READONLY */ |
#endif /* _USE_STRFUNC >= 1*/ |
/programy/C/avr/SDcard/ff.h |
---|
0,0 → 1,339 |
/*--------------------------------------------------------------------------/ |
/ FatFs - FAT file system module include file R0.06 (C)ChaN, 2008 |
/---------------------------------------------------------------------------/ |
/ FatFs module is an experimenal project to implement FAT file system to |
/ cheap microcontrollers. This is a free software and is opened for education, |
/ research and development under license policy of following trems. |
/ |
/ Copyright (C) 2008, ChaN, all right reserved. |
/ |
/ * The FatFs module is a free software and there is no warranty. |
/ * You can use, modify and/or redistribute it for personal, non-profit or |
/ commercial use without any restriction under your responsibility. |
/ * Redistributions of source code must retain the above copyright notice. |
/ |
/---------------------------------------------------------------------------*/ |
#ifndef _FATFS |
#define _MCU_ENDIAN 1 |
/* The _MCU_ENDIAN defines which access method is used to the FAT structure. |
/ 1: Enable word access. |
/ 2: Disable word access and use byte-by-byte access instead. |
/ When the architectural byte order of the MCU is big-endian and/or address |
/ miss-aligned access results incorrect behavior, the _MCU_ENDIAN must be set to 2. |
/ If it is not the case, it can also be set to 1 for good code efficiency. */ |
#define _FS_READONLY 0 |
/* Setting _FS_READONLY to 1 defines read only configuration. This removes |
/ writing functions, f_write, f_sync, f_unlink, f_mkdir, f_chmod, f_rename, |
/ f_truncate and useless f_getfree. */ |
#define _FS_MINIMIZE 0 |
/* The _FS_MINIMIZE option defines minimization level to remove some functions. |
/ 0: Full function. |
/ 1: f_stat, f_getfree, f_unlink, f_mkdir, f_chmod, f_truncate and f_rename are removed. |
/ 2: f_opendir and f_readdir are removed in addition to level 1. |
/ 3: f_lseek is removed in addition to level 2. */ |
#define _USE_STRFUNC 0 |
/* To enable string functions, set _USE_STRFUNC to 1 or 2. */ |
#define _USE_MKFS 1 |
/* When _USE_MKFS is set to 1 and _FS_READONLY is set to 0, f_mkfs function is |
/ enabled. */ |
#define _DRIVES 2 |
/* Number of logical drives to be used. This affects the size of internal table. */ |
#define _MULTI_PARTITION 0 |
/* When _MULTI_PARTITION is set to 0, each logical drive is bound to same |
/ physical drive number and can mount only 1st primaly partition. When it is |
/ set to 1, each logical drive can mount a partition listed in Drives[]. */ |
#define _USE_FSINFO 1 |
/* To enable FSInfo support on FAT32 volume, set _USE_FSINFO to 1. */ |
#define _USE_SJIS 1 |
/* When _USE_SJIS is set to 1, Shift-JIS code transparency is enabled, otherwise |
/ only US-ASCII(7bit) code can be accepted as file/directory name. */ |
#define _USE_NTFLAG 1 |
/* When _USE_NTFLAG is set to 1, upper/lower case of the file name is preserved. |
/ Note that the files are always accessed in case insensitive. */ |
#include "integer.h" |
/* Definitions corresponds to multiple sector size (not tested) */ |
#define S_MAX_SIZ 512U /* Do not change */ |
#if S_MAX_SIZ > 512U |
#define SS(fs) ((fs)->s_size) |
#else |
#define SS(fs) 512U |
#endif |
/* File system object structure */ |
typedef struct _FATFS { |
WORD id; /* File system mount ID */ |
WORD n_rootdir; /* Number of root directory entries */ |
DWORD winsect; /* Current sector appearing in the win[] */ |
DWORD sects_fat; /* Sectors per fat */ |
DWORD max_clust; /* Maximum cluster# + 1 */ |
DWORD fatbase; /* FAT start sector */ |
DWORD dirbase; /* Root directory start sector (cluster# for FAT32) */ |
DWORD database; /* Data start sector */ |
#if !_FS_READONLY |
DWORD last_clust; /* Last allocated cluster */ |
DWORD free_clust; /* Number of free clusters */ |
#if _USE_FSINFO |
DWORD fsi_sector; /* fsinfo sector */ |
BYTE fsi_flag; /* fsinfo dirty flag (1:must be written back) */ |
BYTE pad2; |
#endif |
#endif |
BYTE fs_type; /* FAT sub type */ |
BYTE csize; /* Number of sectors per cluster */ |
#if S_MAX_SIZ > 512U |
WORD s_size; /* Sector size */ |
#endif |
BYTE n_fats; /* Number of FAT copies */ |
BYTE drive; /* Physical drive number */ |
BYTE winflag; /* win[] dirty flag (1:must be written back) */ |
BYTE pad1; |
BYTE win[S_MAX_SIZ]; /* Disk access window for Directory/FAT */ |
} FATFS; |
/* Directory object structure */ |
typedef struct _DIR { |
WORD id; /* Owner file system mount ID */ |
WORD index; /* Current index */ |
FATFS* fs; /* Pointer to the owner file system object */ |
DWORD sclust; /* Start cluster */ |
DWORD clust; /* Current cluster */ |
DWORD sect; /* Current sector */ |
} DIR; |
/* File object structure */ |
typedef struct _FIL { |
WORD id; /* Owner file system mount ID */ |
BYTE flag; /* File status flags */ |
BYTE csect; /* Sector address in the cluster */ |
FATFS* fs; /* Pointer to the owner file system object */ |
DWORD fptr; /* File R/W pointer */ |
DWORD fsize; /* File size */ |
DWORD org_clust; /* File start cluster */ |
DWORD curr_clust; /* Current cluster */ |
DWORD curr_sect; /* Current sector */ |
#if _FS_READONLY == 0 |
DWORD dir_sect; /* Sector containing the directory entry */ |
BYTE* dir_ptr; /* Ponter to the directory entry in the window */ |
#endif |
BYTE buffer[S_MAX_SIZ]; /* File R/W buffer */ |
} FIL; |
/* File status structure */ |
typedef struct _FILINFO { |
DWORD fsize; /* Size */ |
WORD fdate; /* Date */ |
WORD ftime; /* Time */ |
BYTE fattrib; /* Attribute */ |
char fname[8+1+3+1]; /* Name (8.3 format) */ |
} FILINFO; |
/* Definitions corresponds to multi partition */ |
#if _MULTI_PARTITION != 0 /* Multiple partition cfg */ |
typedef struct _PARTITION { |
BYTE pd; /* Physical drive # (0-255) */ |
BYTE pt; /* Partition # (0-3) */ |
} PARTITION; |
extern |
const PARTITION Drives[]; /* Logical drive# to physical location conversion table */ |
#define LD2PD(drv) (Drives[drv].pd) /* Get physical drive# */ |
#define LD2PT(drv) (Drives[drv].pt) /* Get partition# */ |
#else /* Single partition cfg */ |
#define LD2PD(drv) (drv) /* Physical drive# is equal to logical drive# */ |
#define LD2PT(drv) 0 /* Always mounts the 1st partition */ |
#endif |
/* File function return code (FRESULT) */ |
typedef enum { |
FR_OK = 0, /* 0 */ |
FR_NOT_READY, /* 1 */ |
FR_NO_FILE, /* 2 */ |
FR_NO_PATH, /* 3 */ |
FR_INVALID_NAME, /* 4 */ |
FR_INVALID_DRIVE, /* 5 */ |
FR_DENIED, /* 6 */ |
FR_EXIST, /* 7 */ |
FR_RW_ERROR, /* 8 */ |
FR_WRITE_PROTECTED, /* 9 */ |
FR_NOT_ENABLED, /* 10 */ |
FR_NO_FILESYSTEM, /* 11 */ |
FR_INVALID_OBJECT, /* 12 */ |
FR_MKFS_ABORTED /* 13 */ |
} FRESULT; |
/*-----------------------------------------------------*/ |
/* FatFs module application interface */ |
FRESULT f_mount (BYTE, FATFS*); /* Mount/Unmount a logical drive */ |
FRESULT f_open (FIL*, const char*, BYTE); /* Open or create a file */ |
FRESULT f_read (FIL*, void*, UINT, UINT*); /* Read data from a file */ |
FRESULT f_write (FIL*, const void*, UINT, UINT*); /* Write data to a file */ |
FRESULT f_lseek (FIL*, DWORD); /* Move file pointer of a file object */ |
FRESULT f_close (FIL*); /* Close an open file object */ |
FRESULT f_opendir (DIR*, const char*); /* Open an existing directory */ |
FRESULT f_readdir (DIR*, FILINFO*); /* Read a directory item */ |
FRESULT f_stat (const char*, FILINFO*); /* Get file status */ |
FRESULT f_getfree (const char*, DWORD*, FATFS**); /* Get number of free clusters on the drive */ |
FRESULT f_truncate (FIL*); /* Truncate file */ |
FRESULT f_sync (FIL*); /* Flush cached data of a writing file */ |
FRESULT f_unlink (const char*); /* Delete an existing file or directory */ |
FRESULT f_mkdir (const char*); /* Create a new directory */ |
FRESULT f_chmod (const char*, BYTE, BYTE); /* Change file/dir attriburte */ |
FRESULT f_utime (const char*, const FILINFO*); /* Change file/dir timestamp */ |
FRESULT f_rename (const char*, const char*); /* Rename/Move a file or directory */ |
FRESULT f_mkfs (BYTE, BYTE, WORD); /* Create a file system on the drive */ |
#if _USE_STRFUNC |
#define feof(fp) ((fp)->fptr == (fp)->fsize) |
#define EOF -1 |
int fputc (int, FIL*); /* Put a character to the file */ |
int fputs (const char*, FIL*); /* Put a string to the file */ |
int fprintf (FIL*, const char*, ...); /* Put a formatted string to the file */ |
char* fgets (char*, int, FIL*); /* Get a string from the file */ |
#endif |
/* User defined function to give a current time to fatfs module */ |
DWORD get_fattime (void); /* 31-25: Year(0-127 org.1980), 24-21: Month(1-12), 20-16: Day(1-31) */ |
/* 15-11: Hour(0-23), 10-5: Minute(0-59), 4-0: Second(0-29 *2) */ |
/* File access control and file status flags (FIL.flag) */ |
#define FA_READ 0x01 |
#define FA_OPEN_EXISTING 0x00 |
#if _FS_READONLY == 0 |
#define FA_WRITE 0x02 |
#define FA_CREATE_NEW 0x04 |
#define FA_CREATE_ALWAYS 0x08 |
#define FA_OPEN_ALWAYS 0x10 |
#define FA__WRITTEN 0x20 |
#define FA__DIRTY 0x40 |
#endif |
#define FA__ERROR 0x80 |
/* FAT sub type (FATFS.fs_type) */ |
#define FS_FAT12 1 |
#define FS_FAT16 2 |
#define FS_FAT32 3 |
/* File attribute bits for directory entry */ |
#define AM_RDO 0x01 /* Read only */ |
#define AM_HID 0x02 /* Hidden */ |
#define AM_SYS 0x04 /* System */ |
#define AM_VOL 0x08 /* Volume label */ |
#define AM_LFN 0x0F /* LFN entry */ |
#define AM_DIR 0x10 /* Directory */ |
#define AM_ARC 0x20 /* Archive */ |
/* Offset of FAT structure members */ |
#define BS_jmpBoot 0 |
#define BS_OEMName 3 |
#define BPB_BytsPerSec 11 |
#define BPB_SecPerClus 13 |
#define BPB_RsvdSecCnt 14 |
#define BPB_NumFATs 16 |
#define BPB_RootEntCnt 17 |
#define BPB_TotSec16 19 |
#define BPB_Media 21 |
#define BPB_FATSz16 22 |
#define BPB_SecPerTrk 24 |
#define BPB_NumHeads 26 |
#define BPB_HiddSec 28 |
#define BPB_TotSec32 32 |
#define BS_55AA 510 |
#define BS_DrvNum 36 |
#define BS_BootSig 38 |
#define BS_VolID 39 |
#define BS_VolLab 43 |
#define BS_FilSysType 54 |
#define BPB_FATSz32 36 |
#define BPB_ExtFlags 40 |
#define BPB_FSVer 42 |
#define BPB_RootClus 44 |
#define BPB_FSInfo 48 |
#define BPB_BkBootSec 50 |
#define BS_DrvNum32 64 |
#define BS_BootSig32 66 |
#define BS_VolID32 67 |
#define BS_VolLab32 71 |
#define BS_FilSysType32 82 |
#define FSI_LeadSig 0 |
#define FSI_StrucSig 484 |
#define FSI_Free_Count 488 |
#define FSI_Nxt_Free 492 |
#define MBR_Table 446 |
#define DIR_Name 0 |
#define DIR_Attr 11 |
#define DIR_NTres 12 |
#define DIR_CrtTime 14 |
#define DIR_CrtDate 16 |
#define DIR_FstClusHI 20 |
#define DIR_WrtTime 22 |
#define DIR_WrtDate 24 |
#define DIR_FstClusLO 26 |
#define DIR_FileSize 28 |
/* Multi-byte word access macros */ |
#if _MCU_ENDIAN == 1 /* Use word access */ |
#define LD_WORD(ptr) (WORD)(*(WORD*)(BYTE*)(ptr)) |
#define LD_DWORD(ptr) (DWORD)(*(DWORD*)(BYTE*)(ptr)) |
#define ST_WORD(ptr,val) *(WORD*)(BYTE*)(ptr)=(WORD)(val) |
#define ST_DWORD(ptr,val) *(DWORD*)(BYTE*)(ptr)=(DWORD)(val) |
#elif _MCU_ENDIAN == 2 /* Use byte-by-byte access */ |
#define LD_WORD(ptr) (WORD)(((WORD)*(volatile BYTE*)((ptr)+1)<<8)|(WORD)*(volatile BYTE*)(ptr)) |
#define LD_DWORD(ptr) (DWORD)(((DWORD)*(volatile BYTE*)((ptr)+3)<<24)|((DWORD)*(volatile BYTE*)((ptr)+2)<<16)|((WORD)*(volatile BYTE*)((ptr)+1)<<8)|*(volatile BYTE*)(ptr)) |
#define ST_WORD(ptr,val) *(volatile BYTE*)(ptr)=(BYTE)(val); *(volatile BYTE*)((ptr)+1)=(BYTE)((WORD)(val)>>8) |
#define ST_DWORD(ptr,val) *(volatile BYTE*)(ptr)=(BYTE)(val); *(volatile BYTE*)((ptr)+1)=(BYTE)((WORD)(val)>>8); *(volatile BYTE*)((ptr)+2)=(BYTE)((DWORD)(val)>>16); *(volatile BYTE*)((ptr)+3)=(BYTE)((DWORD)(val)>>24) |
#else |
#error Do not forget to set _MCU_ENDIAN properly! |
#endif |
#define _FATFS |
#endif /* _FATFS */ |
/programy/C/avr/SDcard/integer.h |
---|
0,0 → 1,30 |
/*-------------------------------------------*/ |
/* Integer type definitions for FatFs module */ |
/*-------------------------------------------*/ |
#ifndef _INTEGER |
/* These types must be 16-bit, 32-bit or larger integer */ |
typedef int INT; |
typedef unsigned int UINT; |
/* These types must be 8-bit integer */ |
typedef signed char CHAR; |
typedef unsigned char UCHAR; |
typedef unsigned char BYTE; |
/* These types must be 16-bit integer */ |
typedef short SHORT; |
typedef unsigned short USHORT; |
typedef unsigned short WORD; |
/* These types must be 32-bit integer */ |
typedef long LONG; |
typedef unsigned long ULONG; |
typedef unsigned long DWORD; |
/* Boolean type */ |
typedef enum { FALSE = 0, TRUE } BOOL; |
#define _INTEGER |
#endif |
/programy/C/avr/SDcard/main.c |
---|
0,0 → 1,554 |
/*----------------------------------------------------------------------*/ |
/* FAT file system sample project for FatFs R0.06 (C)ChaN, 2008 */ |
/*----------------------------------------------------------------------*/ |
#include <avr/io.h> |
#include <avr/pgmspace.h> |
#include <avr/interrupt.h> |
#include <string.h> |
#include "uart.h" |
#include "xitoa.h" |
#include "ff.h" |
#include "diskio.h" |
#include "rtc.h" |
#include "mmc.c" |
DWORD acc_size; /* Work register for fs command */ |
WORD acc_files, acc_dirs; |
FILINFO finfo; |
BYTE line[120]; /* Console input buffer */ |
FATFS fatfs[2]; /* File system object for each logical drive */ |
BYTE Buff[1024]; /* Working buffer */ |
volatile WORD Timer; /* 100Hz increment timer */ |
#if _MULTI_PARTITION != 0 |
const PARTITION Drives[] = { {0,0}, {0,1} }; |
#endif |
/*---------------------------------------------------------*/ |
/* 100Hz timer interrupt generated by OC2 */ |
/*---------------------------------------------------------*/ |
ISR(TIMER2_COMP_vect) |
{ |
Timer++; /* Performance counter for this module */ |
disk_timerproc(); /* Drive timer procedure of low level disk I/O module */ |
} |
/*---------------------------------------------------------*/ |
/* User Provided Timer Function for FatFs module */ |
/*---------------------------------------------------------*/ |
/* This is a real time clock service to be called from */ |
/* FatFs module. Any valid time must be returned even if */ |
/* the system does not support a real time clock. */ |
/* This is not required in read-only configuration. */ |
DWORD get_fattime () |
{ |
RTC rtc; |
rtc_gettime(&rtc); |
return ((DWORD)(rtc.year - 1980) << 25) |
| ((DWORD)rtc.month << 21) |
| ((DWORD)rtc.mday << 16) |
| ((DWORD)rtc.hour << 11) |
| ((DWORD)rtc.min << 5) |
| ((DWORD)rtc.sec >> 1); |
} |
/*--------------------------------------------------------------------------*/ |
/* Monitor */ |
static |
void put_dump (const BYTE *buff, uint32_t ofs, BYTE cnt) |
{ |
BYTE n; |
xprintf(PSTR("%08lX "), ofs); |
for(n = 0; n < cnt; n++) |
xprintf(PSTR(" %02X"), buff[n]); |
xputc(' '); |
for(n = 0; n < cnt; n++) { |
if ((buff[n] < 0x20)||(buff[n] >= 0x7F)) |
xputc('.'); |
else |
xputc(buff[n]); |
} |
xputc('\n'); |
} |
static |
void get_line (char *buff, int len) |
{ |
char c; |
int idx = 0; |
for (;;) { |
c = uart_get(); |
if (c == '\r') break; |
if ((c == '\b') && idx) { |
idx--; uart_put(c); |
} |
if (((BYTE)c >= ' ') && (idx < len - 1)) { |
buff[idx++] = c; uart_put(c); |
} |
} |
buff[idx] = 0; |
uart_put(c); |
uart_put('\n'); |
} |
static |
FRESULT scan_files (char* path) |
{ |
DIR dirs; |
FRESULT res; |
int i; |
if ((res = f_opendir(&dirs, path)) == FR_OK) { |
i = strlen(path); |
while (((res = f_readdir(&dirs, &finfo)) == FR_OK) && finfo.fname[0]) { |
if (finfo.fattrib & AM_DIR) { |
acc_dirs++; |
*(path+i) = '/'; strcpy(path+i+1, &finfo.fname[0]); |
res = scan_files(path); |
*(path+i) = '\0'; |
if (res != FR_OK) break; |
} else { |
acc_files++; |
acc_size += finfo.fsize; |
} |
} |
} |
return res; |
} |
static |
void put_rc (FRESULT rc) |
{ |
const prog_char *p; |
static const prog_char str[] = |
"OK\0" "NOT_READY\0" "NO_FILE\0" "NO_PATH\0" "INVALID_NAME\0" "INVALID_DRIVE\0" |
"DENIED\0" "EXIST\0" "RW_ERROR\0" "WRITE_PROTECTED\0" "NOT_ENABLED\0" |
"NO_FILESYSTEM\0" "INVALID_OBJECT\0" "MKFS_ABORTED\0"; |
FRESULT i; |
for (p = str, i = 0; i != rc && pgm_read_byte_near(p); i++) { |
while(pgm_read_byte_near(p++)); |
} |
xprintf(PSTR("rc=%u FR_%S\n"), (WORD)rc, p); |
} |
static |
void IoInit () |
{ |
PORTA = 0b11111111; // Port A |
PORTB = 0b10110000; // Port B |
DDRB = 0b11000000; |
PORTC = 0b11111111; // Port C |
PORTD = 0b11111111; // Port D |
PORTE = 0b11110010; // Port E |
DDRE = 0b10000010; |
PORTF = 0b11111111; // Port F |
PORTG = 0b11111; // Port G |
uart_init(); // Initialize UART driver |
/* |
OCR1A = 51; // Timer1: LCD bias generator (OC1B) |
OCR1B = 51; |
TCCR1A = 0b00010000; |
TCCR1B = 0b00001010; |
*/ |
OCR2 = 90-1; // Timer2: 100Hz interval (OC2) |
TCCR2 = 0b00001101; |
TIMSK = 0b10000000; // Enable TC2.oc, interrupt |
rtc_init(); // Initialize RTC |
sei(); |
} |
/*-----------------------------------------------------------------------*/ |
/* Main */ |
int main () |
{ |
char *ptr, *ptr2; |
DWORD p1, p2, p3; |
BYTE res, b1; |
WORD w1; |
UINT s1, s2, cnt; |
DWORD ofs, sect = 0; |
RTC rtc; |
FATFS *fs; |
DIR dir; /* Directory object */ |
FIL file1, file2; /* File object */ |
IoInit(); |
/* Join xitoa module to uart module */ |
xfunc_out = (void (*)(char))uart_put; |
xputs(PSTR("FatFs module test monitor\n")); |
for (;;) { |
xputc('>'); |
get_line(line, sizeof(line)); |
ptr = line; |
switch (*ptr++) { |
case 'd' : |
switch (*ptr++) { |
case 'd' : /* dd <phy_drv#> [<sector>] - Dump secrtor */ |
if (!xatoi(&ptr, &p1)) break; |
if (!xatoi(&ptr, &p2)) p2 = sect; |
res = disk_read((BYTE)p1, Buff, p2, 1); |
if (res) { xprintf(PSTR("rc=%d\n"), (WORD)res); break; } |
sect = p2 + 1; |
xprintf(PSTR("Sector:%lu\n"), p2); |
for (ptr=Buff, ofs = 0; ofs < 0x200; ptr+=16, ofs+=16) |
put_dump(ptr, ofs, 16); |
break; |
case 'i' : /* di <phy_drv#> - Initialize disk */ |
if (!xatoi(&ptr, &p1)) break; |
xprintf(PSTR("rc=%d\n"), (WORD)disk_initialize((BYTE)p1)); |
break; |
case 's' : /* ds <phy_drv#> - Show disk status */ |
if (!xatoi(&ptr, &p1)) break; |
if (disk_ioctl((BYTE)p1, GET_SECTOR_COUNT, &p2) == RES_OK) |
{ xprintf(PSTR("Drive size: %lu sectors\n"), p2); } |
if (disk_ioctl((BYTE)p1, GET_SECTOR_SIZE, &w1) == RES_OK) |
{ xprintf(PSTR("Sector size: %u\n"), w1); } |
if (disk_ioctl((BYTE)p1, GET_BLOCK_SIZE, &p2) == RES_OK) |
{ xprintf(PSTR("Erase block size: %lu sectors\n"), p2); } |
if (disk_ioctl((BYTE)p1, MMC_GET_TYPE, &b1) == RES_OK) |
{ xprintf(PSTR("MMC/SDC type: %u\n"), b1); } |
if (disk_ioctl((BYTE)p1, MMC_GET_CSD, Buff) == RES_OK) |
{ xputs(PSTR("CSD:\n")); put_dump(Buff, 0, 16); } |
if (disk_ioctl((BYTE)p1, MMC_GET_CID, Buff) == RES_OK) |
{ xputs(PSTR("CID:\n")); put_dump(Buff, 0, 16); } |
if (disk_ioctl((BYTE)p1, MMC_GET_OCR, Buff) == RES_OK) |
{ xputs(PSTR("OCR:\n")); put_dump(Buff, 0, 4); } |
if (disk_ioctl((BYTE)p1, MMC_GET_SDSTAT, Buff) == RES_OK) { |
xputs(PSTR("SD Status:\n")); |
for (s1 = 0; s1 < 64; s1 += 16) put_dump(Buff+s1, s1, 16); |
} |
if (disk_ioctl((BYTE)p1, ATA_GET_MODEL, line) == RES_OK) |
{ line[40] = '\0'; xprintf(PSTR("Model: %s\n"), line); } |
if (disk_ioctl((BYTE)p1, ATA_GET_SN, line) == RES_OK) |
{ line[20] = '\0'; xprintf(PSTR("S/N: %s\n"), line); } |
break; |
} |
break; |
case 'b' : |
switch (*ptr++) { |
case 'd' : /* bd <addr> - Dump R/W buffer */ |
if (!xatoi(&ptr, &p1)) break; |
for (ptr=&Buff[p1], ofs = p1, cnt = 32; cnt; cnt--, ptr+=16, ofs+=16) |
put_dump(ptr, ofs, 16); |
break; |
case 'e' : /* be <addr> [<data>] ... - Edit R/W buffer */ |
if (!xatoi(&ptr, &p1)) break; |
if (xatoi(&ptr, &p2)) { |
do { |
Buff[p1++] = (BYTE)p2; |
} while (xatoi(&ptr, &p2)); |
break; |
} |
for (;;) { |
xprintf(PSTR("%04X %02X-"), (WORD)(p1), (WORD)Buff[p1]); |
get_line(line, sizeof(line)); |
ptr = line; |
if (*ptr == '.') break; |
if (*ptr < ' ') { p1++; continue; } |
if (xatoi(&ptr, &p2)) |
Buff[p1++] = (BYTE)p2; |
else |
xputs(PSTR("???\n")); |
} |
break; |
case 'r' : /* br <phy_drv#> <sector> [<n>] - Read disk into R/W buffer */ |
if (!xatoi(&ptr, &p1)) break; |
if (!xatoi(&ptr, &p2)) break; |
if (!xatoi(&ptr, &p3)) p3 = 1; |
xprintf(PSTR("rc=%u\n"), (WORD)disk_read((BYTE)p1, Buff, p2, p3)); |
break; |
case 'w' : /* bw <phy_drv#> <sector> [<n>] - Write R/W buffer into disk */ |
if (!xatoi(&ptr, &p1)) break; |
if (!xatoi(&ptr, &p2)) break; |
if (!xatoi(&ptr, &p3)) p3 = 1; |
xprintf(PSTR("rc=%u\n"), (WORD)disk_write((BYTE)p1, Buff, p2, p3)); |
break; |
case 'f' : /* bf <n> - Fill working buffer */ |
if (!xatoi(&ptr, &p1)) break; |
memset(Buff, (BYTE)p1, sizeof(Buff)); |
break; |
} |
break; |
case 'f' : |
switch (*ptr++) { |
case 'i' : /* fi <log drv#> - Initialize logical drive */ |
if (!xatoi(&ptr, &p1)) break; |
put_rc(f_mount((BYTE)p1, &fatfs[p1])); |
break; |
case 's' : /* fs [<path>] - Show logical drive status */ |
res = f_getfree(ptr, &p2, &fs); |
if (res) { put_rc(res); break; } |
xprintf(PSTR("FAT type = %u\nBytes/Cluster = %lu\nNumber of FATs = %u\n" |
"Root DIR entries = %u\nSectors/FAT = %lu\nNumber of clusters = %lu\n" |
"FAT start (lba) = %lu\nDIR start (lba,clustor) = %lu\nData start (lba) = %lu\n"), |
(WORD)fs->fs_type, (DWORD)fs->csize * 512, (WORD)fs->n_fats, |
fs->n_rootdir, (DWORD)fs->sects_fat, (DWORD)fs->max_clust - 2, |
fs->fatbase, fs->dirbase, fs->database |
); |
acc_size = acc_files = acc_dirs = 0; |
res = scan_files(ptr); |
if (res) { put_rc(res); break; } |
xprintf(PSTR("%u files, %lu bytes.\n%u folders.\n" |
"%lu KB total disk space.\n%lu KB available.\n"), |
acc_files, acc_size, acc_dirs, |
(fs->max_clust - 2) * (fs->csize / 2), p2 * (fs->csize / 2) |
); |
break; |
case 'l' : /* fl [<path>] - Directory listing */ |
res = f_opendir(&dir, ptr); |
if (res) { put_rc(res); break; } |
p1 = s1 = s2 = 0; |
for(;;) { |
res = f_readdir(&dir, &finfo); |
if ((res != FR_OK) || !finfo.fname[0]) break; |
if (finfo.fattrib & AM_DIR) { |
s2++; |
} else { |
s1++; p1 += finfo.fsize; |
} |
xprintf(PSTR("%c%c%c%c%c %u/%02u/%02u %02u:%02u %9lu %s\n"), |
(finfo.fattrib & AM_DIR) ? 'D' : '-', |
(finfo.fattrib & AM_RDO) ? 'R' : '-', |
(finfo.fattrib & AM_HID) ? 'H' : '-', |
(finfo.fattrib & AM_SYS) ? 'S' : '-', |
(finfo.fattrib & AM_ARC) ? 'A' : '-', |
(finfo.fdate >> 9) + 1980, (finfo.fdate >> 5) & 15, finfo.fdate & 31, |
(finfo.ftime >> 11), (finfo.ftime >> 5) & 63, |
finfo.fsize, &(finfo.fname[0])); |
} |
xprintf(PSTR("%4u File(s),%10lu bytes total\n%4u Dir(s)"), s1, p1, s2); |
if (f_getfree(ptr, &p1, &fs) == FR_OK) |
xprintf(PSTR(", %10luK bytes free\n"), p1 * fs->csize / 2); |
break; |
case 'o' : /* fo <mode> <name> - Open a file */ |
if (!xatoi(&ptr, &p1)) break; |
put_rc(f_open(&file1, ptr, (BYTE)p1)); |
break; |
case 'c' : /* fc - Close a file */ |
put_rc(f_close(&file1)); |
break; |
case 'e' : /* fe - Seek file pointer */ |
if (!xatoi(&ptr, &p1)) break; |
res = f_lseek(&file1, p1); |
put_rc(res); |
if (res == FR_OK) |
xprintf(PSTR("fptr = %lu(0x%lX)\n"), file1.fptr, file1.fptr); |
break; |
case 'r' : /* fr <len> - read file */ |
if (!xatoi(&ptr, &p1)) break; |
p2 = 0; |
Timer = 0; |
while (p1) { |
if (p1 >= sizeof(Buff)) { cnt = sizeof(Buff); p1 -= sizeof(Buff); } |
else { cnt = (WORD)p1; p1 = 0; } |
res = f_read(&file1, Buff, cnt, &s2); |
if (res != FR_OK) { put_rc(res); break; } |
p2 += s2; |
if (cnt != s2) break; |
} |
s2 = Timer; |
xprintf(PSTR("%lu bytes read with %lu bytes/sec.\n"), p2, p2 * 100 / s2); |
break; |
case 'd' : /* fd <len> - read and dump file from current fp */ |
if (!xatoi(&ptr, &p1)) break; |
ofs = file1.fptr; |
while (p1) { |
if (p1 >= 16) { cnt = 16; p1 -= 16; } |
else { cnt = (WORD)p1; p1 = 0; } |
res = f_read(&file1, Buff, cnt, &cnt); |
if (res != FR_OK) { put_rc(res); break; } |
if (!cnt) break; |
put_dump(Buff, ofs, cnt); |
ofs += 16; |
} |
break; |
case 'w' : /* fw <len> <val> - write file */ |
if (!xatoi(&ptr, &p1) || !xatoi(&ptr, &p2)) break; |
memset(Buff, (BYTE)p2, sizeof(Buff)); |
p2 = 0; |
Timer = 0; |
while (p1) { |
if (p1 >= sizeof(Buff)) { cnt = sizeof(Buff); p1 -= sizeof(Buff); } |
else { cnt = (WORD)p1; p1 = 0; } |
res = f_write(&file1, Buff, cnt, &s2); |
if (res != FR_OK) { put_rc(res); break; } |
p2 += s2; |
if (cnt != s2) break; |
} |
s2 = Timer; |
xprintf(PSTR("%lu bytes written with %lu bytes/sec.\n"), p2, p2 * 100 / s2); |
break; |
case 'v' : /* fv - Truncate file */ |
put_rc(f_truncate(&file1)); |
break; |
case 'n' : /* fn <old_name> <new_name> - Change file/dir name */ |
while (*ptr == ' ') ptr++; |
ptr2 = strchr(ptr, ' '); |
if (!ptr2) break; |
*ptr2++ = 0; |
while (*ptr2 == ' ') ptr2++; |
put_rc(f_rename(ptr, ptr2)); |
break; |
case 'u' : /* fu <name> - Unlink a file or dir */ |
put_rc(f_unlink(ptr)); |
break; |
case 'k' : /* fk <name> - Create a directory */ |
put_rc(f_mkdir(ptr)); |
break; |
case 'a' : /* fa <atrr> <mask> <name> - Change file/dir attribute */ |
if (!xatoi(&ptr, &p1) || !xatoi(&ptr, &p2)) break; |
put_rc(f_chmod(ptr, p1, p2)); |
break; |
case 't' : /* ft <year> <month> <day> <hour> <min> <sec> <name> */ |
if (!xatoi(&ptr, &p1) || !xatoi(&ptr, &p2) || !xatoi(&ptr, &p3)) break; |
finfo.fdate = ((p1 - 1980) << 9) | ((p2 & 15) << 5) | (p3 & 31); |
if (!xatoi(&ptr, &p1) || !xatoi(&ptr, &p2) || !xatoi(&ptr, &p3)) break; |
finfo.ftime = ((p1 & 31) << 11) | ((p1 & 63) << 5) | ((p1 >> 1) & 31); |
put_rc(f_utime(ptr, &finfo)); |
break; |
case 'x' : /* fx <src_name> <dst_name> - Copy file */ |
while (*ptr == ' ') ptr++; |
ptr2 = strchr(ptr, ' '); |
if (!ptr2) break; |
*ptr2++ = 0; |
xprintf(PSTR("Opening \"%s\""), ptr); |
res = f_open(&file1, ptr, FA_OPEN_EXISTING | FA_READ); |
if (res) { |
put_rc(res); |
break; |
} |
xprintf(PSTR("\nCreating \"%s\""), ptr2); |
res = f_open(&file2, ptr2, FA_CREATE_ALWAYS | FA_WRITE); |
if (res) { |
put_rc(res); |
f_close(&file1); |
break; |
} |
xprintf(PSTR("\nCopying...")); |
p1 = 0; |
for (;;) { |
res = f_read(&file1, Buff, sizeof(Buff), &s1); |
if (res || s1 == 0) break; /* error or eof */ |
res = f_write(&file2, Buff, s1, &s2); |
p1 += s2; |
if (res || s2 < s1) break; /* error or disk full */ |
} |
if (res) put_rc(res); |
xprintf(PSTR("\n%lu bytes copied.\n"), p1); |
f_close(&file1); |
f_close(&file2); |
break; |
#if _USE_MKFS |
case 'm' : /* fm <logi drv#> <part type> <bytes/clust> - Create file system */ |
if (!xatoi(&ptr, &p1) || !xatoi(&ptr, &p2) || !xatoi(&ptr, &p3)) break; |
xprintf(PSTR("The drive %u will be formatted. Are you sure? (Y/n)="), (WORD)p1); |
get_line(ptr, sizeof(line)); |
if (*ptr == 'Y') put_rc(f_mkfs((BYTE)p1, (BYTE)p2, (WORD)p3)); |
break; |
#endif |
} |
break; |
case 't' : /* t [<year> <mon> <mday> <hour> <min> <sec>] */ |
if (xatoi(&ptr, &p1)) { |
rtc.year = (WORD)p1; |
xatoi(&ptr, &p1); rtc.month = (BYTE)p1; |
xatoi(&ptr, &p1); rtc.mday = (BYTE)p1; |
xatoi(&ptr, &p1); rtc.hour = (BYTE)p1; |
xatoi(&ptr, &p1); rtc.min = (BYTE)p1; |
if (!xatoi(&ptr, &p1)) break; |
rtc.sec = (BYTE)p1; |
rtc_settime(&rtc); |
} |
rtc_gettime(&rtc); |
xprintf(PSTR("%u/%u/%u %02u:%02u:%02u\n"), rtc.year, rtc.month, rtc.mday, rtc.hour, rtc.min, rtc.sec); |
break; |
} |
} |
} |
/programy/C/avr/SDcard/mmc.c |
---|
0,0 → 1,597 |
/*-----------------------------------------------------------------------*/ |
/* MMC/SDSC/SDHC (in SPI mode) control module (C)ChaN, 2007 */ |
/*-----------------------------------------------------------------------*/ |
/* Only rcvr_spi(), xmit_spi(), disk_timerproc() and some macros */ |
/* are platform dependent. */ |
/*-----------------------------------------------------------------------*/ |
#include <avr/io.h> |
#include "diskio.h" |
/* Definitions for MMC/SDC command */ |
#define CMD0 (0x40+0) /* GO_IDLE_STATE */ |
#define CMD1 (0x40+1) /* SEND_OP_COND (MMC) */ |
#define ACMD41 (0xC0+41) /* SEND_OP_COND (SDC) */ |
#define CMD8 (0x40+8) /* SEND_IF_COND */ |
#define CMD9 (0x40+9) /* SEND_CSD */ |
#define CMD10 (0x40+10) /* SEND_CID */ |
#define CMD12 (0x40+12) /* STOP_TRANSMISSION */ |
#define ACMD13 (0xC0+13) /* SD_STATUS (SDC) */ |
#define CMD16 (0x40+16) /* SET_BLOCKLEN */ |
#define CMD17 (0x40+17) /* READ_SINGLE_BLOCK */ |
#define CMD18 (0x40+18) /* READ_MULTIPLE_BLOCK */ |
#define CMD23 (0x40+23) /* SET_BLOCK_COUNT (MMC) */ |
#define ACMD23 (0xC0+23) /* SET_WR_BLK_ERASE_COUNT (SDC) */ |
#define CMD24 (0x40+24) /* WRITE_BLOCK */ |
#define CMD25 (0x40+25) /* WRITE_MULTIPLE_BLOCK */ |
#define CMD55 (0x40+55) /* APP_CMD */ |
#define CMD58 (0x40+58) /* READ_OCR */ |
/* Port Controls (Platform dependent) */ |
#define SELECT() PORTB &= ~1 /* MMC CS = L */ |
#define DESELECT() PORTB |= 1 /* MMC CS = H */ |
#define SOCKPORT PINB /* Socket contact port */ |
#define SOCKWP 0x20 /* Write protect switch (PB5) */ |
#define SOCKINS 0x10 /* Card detect switch (PB4) */ |
/*-------------------------------------------------------------------------- |
Module Private Functions |
---------------------------------------------------------------------------*/ |
static volatile |
DSTATUS Stat = STA_NOINIT; /* Disk status */ |
static volatile |
BYTE Timer1, Timer2; /* 100Hz decrement timer */ |
static |
BYTE CardType; /* b0:MMC, b1:SDv1, b2:SDv2, b3:Block addressing */ |
/*-----------------------------------------------------------------------*/ |
/* Transmit a byte to MMC via SPI (Platform dependent) */ |
/*-----------------------------------------------------------------------*/ |
#define xmit_spi(dat) SPDR=(dat); loop_until_bit_is_set(SPSR,SPIF) |
/*-----------------------------------------------------------------------*/ |
/* Receive a byte from MMC via SPI (Platform dependent) */ |
/*-----------------------------------------------------------------------*/ |
static |
BYTE rcvr_spi (void) |
{ |
SPDR = 0xFF; |
loop_until_bit_is_set(SPSR, SPIF); |
return SPDR; |
} |
/* Alternative macro to receive data fast */ |
#define rcvr_spi_m(dst) SPDR=0xFF; loop_until_bit_is_set(SPSR,SPIF); *(dst)=SPDR |
/*-----------------------------------------------------------------------*/ |
/* Wait for card ready */ |
/*-----------------------------------------------------------------------*/ |
static |
BYTE wait_ready (void) |
{ |
BYTE res; |
Timer2 = 50; /* Wait for ready in timeout of 500ms */ |
rcvr_spi(); |
do |
res = rcvr_spi(); |
while ((res != 0xFF) && Timer2); |
return res; |
} |
/*-----------------------------------------------------------------------*/ |
/* Deselect the card and release SPI bus */ |
/*-----------------------------------------------------------------------*/ |
static |
void release_spi (void) |
{ |
DESELECT(); |
rcvr_spi(); |
} |
/*-----------------------------------------------------------------------*/ |
/* Power Control (Platform dependent) */ |
/*-----------------------------------------------------------------------*/ |
/* When the target system does not support socket power control, there */ |
/* is nothing to do in these functions and chk_power always returns 1. */ |
static |
void power_on (void) |
{ |
PORTE &= ~0x80; /* Socket power ON */ |
for (Timer1 = 3; Timer1; ); /* Wait for 30ms */ |
PORTB = 0b10110101; /* Enable drivers */ |
DDRB = 0b11000111; |
SPCR = 0b01010000; /* Initialize SPI port (Mode 0) */ |
SPSR = 0b00000001; |
} |
static |
void power_off (void) |
{ |
SELECT(); /* Wait for card ready */ |
wait_ready(); |
release_spi(); |
SPCR = 0; /* Disable SPI function */ |
DDRB = 0b11000000; /* Disable drivers */ |
PORTB = 0b10110000; |
PORTE |= 0x80; /* Socket power OFF */ |
Stat |= STA_NOINIT; /* Set STA_NOINIT */ |
} |
static |
int chk_power(void) /* Socket power state: 0=off, 1=on */ |
{ |
return (PORTE & 0x80) ? 0 : 1; |
} |
/*-----------------------------------------------------------------------*/ |
/* Receive a data packet from MMC */ |
/*-----------------------------------------------------------------------*/ |
static |
BOOL rcvr_datablock ( |
BYTE *buff, /* Data buffer to store received data */ |
UINT btr /* Byte count (must be multiple of 4) */ |
) |
{ |
BYTE token; |
Timer1 = 10; |
do { /* Wait for data packet in timeout of 100ms */ |
token = rcvr_spi(); |
} while ((token == 0xFF) && Timer1); |
if(token != 0xFE) return FALSE; /* If not valid data token, retutn with error */ |
do { /* Receive the data block into buffer */ |
rcvr_spi_m(buff++); |
rcvr_spi_m(buff++); |
rcvr_spi_m(buff++); |
rcvr_spi_m(buff++); |
} while (btr -= 4); |
rcvr_spi(); /* Discard CRC */ |
rcvr_spi(); |
return TRUE; /* Return with success */ |
} |
/*-----------------------------------------------------------------------*/ |
/* Send a data packet to MMC */ |
/*-----------------------------------------------------------------------*/ |
#if _READONLY == 0 |
static |
BOOL xmit_datablock ( |
const BYTE *buff, /* 512 byte data block to be transmitted */ |
BYTE token /* Data/Stop token */ |
) |
{ |
BYTE resp, wc; |
if (wait_ready() != 0xFF) return FALSE; |
xmit_spi(token); /* Xmit data token */ |
if (token != 0xFD) { /* Is data token */ |
wc = 0; |
do { /* Xmit the 512 byte data block to MMC */ |
xmit_spi(*buff++); |
xmit_spi(*buff++); |
} while (--wc); |
xmit_spi(0xFF); /* CRC (Dummy) */ |
xmit_spi(0xFF); |
resp = rcvr_spi(); /* Reveive data response */ |
if ((resp & 0x1F) != 0x05) /* If not accepted, return with error */ |
return FALSE; |
} |
return TRUE; |
} |
#endif /* _READONLY */ |
/*-----------------------------------------------------------------------*/ |
/* Send a command packet to MMC */ |
/*-----------------------------------------------------------------------*/ |
static |
BYTE send_cmd ( |
BYTE cmd, /* Command byte */ |
DWORD arg /* Argument */ |
) |
{ |
BYTE n, res; |
if (cmd & 0x80) { /* ACMD<n> is the command sequense of CMD55-CMD<n> */ |
cmd &= 0x7F; |
res = send_cmd(CMD55, 0); |
if (res > 1) return res; |
} |
/* Select the card and wait for ready */ |
DESELECT(); |
SELECT(); |
if (wait_ready() != 0xFF) return 0xFF; |
/* Send command packet */ |
xmit_spi(cmd); /* Start + Command index */ |
xmit_spi((BYTE)(arg >> 24)); /* Argument[31..24] */ |
xmit_spi((BYTE)(arg >> 16)); /* Argument[23..16] */ |
xmit_spi((BYTE)(arg >> 8)); /* Argument[15..8] */ |
xmit_spi((BYTE)arg); /* Argument[7..0] */ |
n = 0x01; /* Dummy CRC + Stop */ |
if (cmd == CMD0) n = 0x95; /* Valid CRC for CMD0(0) */ |
if (cmd == CMD8) n = 0x87; /* Valid CRC for CMD8(0x1AA) */ |
xmit_spi(n); |
/* Receive command response */ |
if (cmd == CMD12) rcvr_spi(); /* Skip a stuff byte when stop reading */ |
n = 10; /* Wait for a valid response in timeout of 10 attempts */ |
do |
res = rcvr_spi(); |
while ((res & 0x80) && --n); |
return res; /* Return with the response value */ |
} |
/*-------------------------------------------------------------------------- |
Public Functions |
---------------------------------------------------------------------------*/ |
/*-----------------------------------------------------------------------*/ |
/* Initialize Disk Drive */ |
/*-----------------------------------------------------------------------*/ |
DSTATUS disk_initialize ( |
BYTE drv /* Physical drive nmuber (0) */ |
) |
{ |
BYTE n, cmd, ty, ocr[4]; |
if (drv) return STA_NOINIT; /* Supports only single drive */ |
if (Stat & STA_NODISK) return Stat; /* No card in the socket */ |
power_on(); /* Force socket power on */ |
for (n = 10; n; n--) rcvr_spi(); /* 80 dummy clocks */ |
ty = 0; |
if (send_cmd(CMD0, 0) == 1) { /* Enter Idle state */ |
Timer1 = 100; /* Initialization timeout of 1000 msec */ |
if (send_cmd(CMD8, 0x1AA) == 1) { /* SDHC */ |
for (n = 0; n < 4; n++) ocr[n] = rcvr_spi(); /* Get trailing return value of R7 resp */ |
if (ocr[2] == 0x01 && ocr[3] == 0xAA) { /* The card can work at vdd range of 2.7-3.6V */ |
while (Timer1 && send_cmd(ACMD41, 1UL << 30)); /* Wait for leaving idle state (ACMD41 with HCS bit) */ |
if (Timer1 && send_cmd(CMD58, 0) == 0) { /* Check CCS bit in the OCR */ |
for (n = 0; n < 4; n++) ocr[n] = rcvr_spi(); |
ty = (ocr[0] & 0x40) ? 12 : 4; |
} |
} |
} else { /* SDSC or MMC */ |
if (send_cmd(ACMD41, 0) <= 1) { |
ty = 2; cmd = ACMD41; /* SDSC */ |
} else { |
ty = 1; cmd = CMD1; /* MMC */ |
} |
while (Timer1 && send_cmd(cmd, 0)); /* Wait for leaving idle state */ |
if (!Timer1 || send_cmd(CMD16, 512) != 0) /* Set R/W block length to 512 */ |
ty = 0; |
} |
} |
CardType = ty; |
release_spi(); |
if (ty) { /* Initialization succeded */ |
Stat &= ~STA_NOINIT; /* Clear STA_NOINIT */ |
} else { /* Initialization failed */ |
power_off(); |
} |
return Stat; |
} |
/*-----------------------------------------------------------------------*/ |
/* Get Disk Status */ |
/*-----------------------------------------------------------------------*/ |
DSTATUS disk_status ( |
BYTE drv /* Physical drive nmuber (0) */ |
) |
{ |
if (drv) return STA_NOINIT; /* Supports only single drive */ |
return Stat; |
} |
/*-----------------------------------------------------------------------*/ |
/* Read Sector(s) */ |
/*-----------------------------------------------------------------------*/ |
DRESULT disk_read ( |
BYTE drv, /* Physical drive nmuber (0) */ |
BYTE *buff, /* Pointer to the data buffer to store read data */ |
DWORD sector, /* Start sector number (LBA) */ |
BYTE count /* Sector count (1..255) */ |
) |
{ |
if (drv || !count) return RES_PARERR; |
if (Stat & STA_NOINIT) return RES_NOTRDY; |
if (!(CardType & 8)) sector *= 512; /* Convert to byte address if needed */ |
if (count == 1) { /* Single block read */ |
if ((send_cmd(CMD17, sector) == 0) /* READ_SINGLE_BLOCK */ |
&& rcvr_datablock(buff, 512)) |
count = 0; |
} |
else { /* Multiple block read */ |
if (send_cmd(CMD18, sector) == 0) { /* READ_MULTIPLE_BLOCK */ |
do { |
if (!rcvr_datablock(buff, 512)) break; |
buff += 512; |
} while (--count); |
send_cmd(CMD12, 0); /* STOP_TRANSMISSION */ |
} |
} |
release_spi(); |
return count ? RES_ERROR : RES_OK; |
} |
/*-----------------------------------------------------------------------*/ |
/* Write Sector(s) */ |
/*-----------------------------------------------------------------------*/ |
#if _READONLY == 0 |
DRESULT disk_write ( |
BYTE drv, /* Physical drive nmuber (0) */ |
const BYTE *buff, /* Pointer to the data to be written */ |
DWORD sector, /* Start sector number (LBA) */ |
BYTE count /* Sector count (1..255) */ |
) |
{ |
if (drv || !count) return RES_PARERR; |
if (Stat & STA_NOINIT) return RES_NOTRDY; |
if (Stat & STA_PROTECT) return RES_WRPRT; |
if (!(CardType & 8)) sector *= 512; /* Convert to byte address if needed */ |
if (count == 1) { /* Single block write */ |
if ((send_cmd(CMD24, sector) == 0) /* WRITE_BLOCK */ |
&& xmit_datablock(buff, 0xFE)) |
count = 0; |
} |
else { /* Multiple block write */ |
if (CardType & 6) send_cmd(ACMD23, count); |
if (send_cmd(CMD25, sector) == 0) { /* WRITE_MULTIPLE_BLOCK */ |
do { |
if (!xmit_datablock(buff, 0xFC)) break; |
buff += 512; |
} while (--count); |
if (!xmit_datablock(0, 0xFD)) /* STOP_TRAN token */ |
count = 1; |
} |
} |
release_spi(); |
return count ? RES_ERROR : RES_OK; |
} |
#endif /* _READONLY == 0 */ |
/*-----------------------------------------------------------------------*/ |
/* Miscellaneous Functions */ |
/*-----------------------------------------------------------------------*/ |
#if _USE_IOCTL != 0 |
DRESULT disk_ioctl ( |
BYTE drv, /* Physical drive nmuber (0) */ |
BYTE ctrl, /* Control code */ |
void *buff /* Buffer to send/receive control data */ |
) |
{ |
DRESULT res; |
BYTE n, csd[16], *ptr = buff; |
WORD csize; |
if (drv) return RES_PARERR; |
res = RES_ERROR; |
if (ctrl == CTRL_POWER) { |
switch (*ptr) { |
case 0: /* Sub control code == 0 (POWER_OFF) */ |
if (chk_power()) |
power_off(); /* Power off */ |
res = RES_OK; |
break; |
case 1: /* Sub control code == 1 (POWER_ON) */ |
power_on(); /* Power on */ |
res = RES_OK; |
break; |
case 2: /* Sub control code == 2 (POWER_GET) */ |
*(ptr+1) = (BYTE)chk_power(); |
res = RES_OK; |
break; |
default : |
res = RES_PARERR; |
} |
} |
else { |
if (Stat & STA_NOINIT) return RES_NOTRDY; |
switch (ctrl) { |
case CTRL_SYNC : /* Make sure that no pending write process */ |
SELECT(); |
if (wait_ready() == 0xFF) |
res = RES_OK; |
break; |
case GET_SECTOR_COUNT : /* Get number of sectors on the disk (DWORD) */ |
if ((send_cmd(CMD9, 0) == 0) && rcvr_datablock(csd, 16)) { |
if ((csd[0] >> 6) == 1) { /* SDC ver 2.00 */ |
csize = csd[9] + ((WORD)csd[8] << 8) + 1; |
*(DWORD*)buff = (DWORD)csize << 10; |
} else { /* SDC ver 1.XX or MMC*/ |
n = (csd[5] & 15) + ((csd[10] & 128) >> 7) + ((csd[9] & 3) << 1) + 2; |
csize = (csd[8] >> 6) + ((WORD)csd[7] << 2) + ((WORD)(csd[6] & 3) << 10) + 1; |
*(DWORD*)buff = (DWORD)csize << (n - 9); |
} |
res = RES_OK; |
} |
break; |
case GET_SECTOR_SIZE : /* Get R/W sector size (WORD) */ |
*(WORD*)buff = 512; |
res = RES_OK; |
break; |
case GET_BLOCK_SIZE : /* Get erase block size in unit of sector (DWORD) */ |
if (CardType & 4) { /* SDC ver 2.00 */ |
if (send_cmd(ACMD13, 0) == 0) { /* Read SD status */ |
rcvr_spi(); |
if (rcvr_datablock(csd, 16)) { /* Read partial block */ |
for (n = 64 - 16; n; n--) rcvr_spi(); /* Purge trailing data */ |
*(DWORD*)buff = 16UL << (csd[10] >> 4); |
res = RES_OK; |
} |
} |
} else { /* SDC ver 1.XX or MMC */ |
if ((send_cmd(CMD9, 0) == 0) && rcvr_datablock(csd, 16)) { /* Read CSD */ |
if (CardType & 2) { /* SDC ver 1.XX */ |
*(DWORD*)buff = (((csd[10] & 63) << 1) + ((WORD)(csd[11] & 128) >> 7) + 1) << ((csd[13] >> 6) - 1); |
} else { /* MMC */ |
*(DWORD*)buff = ((WORD)((csd[10] & 124) >> 2) + 1) * (((csd[11] & 3) << 3) + ((csd[11] & 224) >> 5) + 1); |
} |
res = RES_OK; |
} |
} |
break; |
case MMC_GET_TYPE : /* Get card type flags (1 byte) */ |
*ptr = CardType; |
res = RES_OK; |
break; |
case MMC_GET_CSD : /* Receive CSD as a data block (16 bytes) */ |
if (send_cmd(CMD9, 0) == 0 /* READ_CSD */ |
&& rcvr_datablock(ptr, 16)) |
res = RES_OK; |
break; |
case MMC_GET_CID : /* Receive CID as a data block (16 bytes) */ |
if (send_cmd(CMD10, 0) == 0 /* READ_CID */ |
&& rcvr_datablock(ptr, 16)) |
res = RES_OK; |
break; |
case MMC_GET_OCR : /* Receive OCR as an R3 resp (4 bytes) */ |
if (send_cmd(CMD58, 0) == 0) { /* READ_OCR */ |
for (n = 4; n; n--) *ptr++ = rcvr_spi(); |
res = RES_OK; |
} |
break; |
case MMC_GET_SDSTAT : /* Receive SD statsu as a data block (64 bytes) */ |
if (send_cmd(ACMD13, 0) == 0) { /* SD_STATUS */ |
rcvr_spi(); |
if (rcvr_datablock(ptr, 64)) |
res = RES_OK; |
} |
break; |
default: |
res = RES_PARERR; |
} |
release_spi(); |
} |
return res; |
} |
#endif /* _USE_IOCTL != 0 */ |
/*-----------------------------------------------------------------------*/ |
/* Device Timer Interrupt Procedure (Platform dependent) */ |
/*-----------------------------------------------------------------------*/ |
/* This function must be called in period of 10ms */ |
void disk_timerproc (void) |
{ |
static BYTE pv; |
BYTE n, s; |
n = Timer1; /* 100Hz decrement timer */ |
if (n) Timer1 = --n; |
n = Timer2; |
if (n) Timer2 = --n; |
n = pv; |
pv = SOCKPORT & (SOCKWP | SOCKINS); /* Sample socket switch */ |
if (n == pv) { /* Have contacts stabled? */ |
s = Stat; |
if (pv & SOCKWP) /* WP is H (write protected) */ |
s |= STA_PROTECT; |
else /* WP is L (write enabled) */ |
s &= ~STA_PROTECT; |
if (pv & SOCKINS) /* INS = H (Socket empty) */ |
s |= (STA_NODISK | STA_NOINIT); |
else /* INS = L (Card inserted) */ |
s &= ~STA_NODISK; |
Stat = s; |
} |
} |
/programy/C/avr/SDcard/rtc.c |
---|
0,0 → 1,252 |
/*--------------------------------------------------------------------------*/ |
/* RTC controls */ |
#include <avr/io.h> |
#include <string.h> |
#include "rtc.h" |
#define SCL_LOW() DDRE |= 0x04 /* SCL = LOW */ |
#define SCL_HIGH() DDRE &= 0xFB /* SCL = High-Z */ |
#define SCL_VAL ((PINE & 0x04) ? 1 : 0) /* SCL input level */ |
#define SDA_LOW() DDRE |= 0x08 /* SDA = LOW */ |
#define SDA_HIGH() DDRE &= 0xF7 /* SDA = High-Z */ |
#define SDA_VAL ((PINE & 0x08) ? 1 : 0) /* SDA input level */ |
static |
void iic_delay (void) |
{ |
int n; |
BYTE d; |
for (n = 4; n; n--) d = PINE; |
} |
/* Generate start condition on the IIC bus */ |
static |
void iic_start (void) |
{ |
SDA_HIGH(); |
iic_delay(); |
SCL_HIGH(); |
iic_delay(); |
SDA_LOW(); |
iic_delay(); |
SCL_LOW(); |
iic_delay(); |
} |
/* Generate stop condition on the IIC bus */ |
static |
void iic_stop (void) |
{ |
SDA_LOW(); |
iic_delay(); |
SCL_HIGH(); |
iic_delay(); |
SDA_HIGH(); |
iic_delay(); |
} |
/* Send a byte to the IIC bus */ |
static |
BOOL iic_send (BYTE dat) |
{ |
BYTE b = 0x80; |
BOOL ack; |
do { |
if (dat & b) { /* SDA = Z/L */ |
SDA_HIGH(); |
} else { |
SDA_LOW(); |
} |
iic_delay(); |
SCL_HIGH(); |
iic_delay(); |
SCL_LOW(); |
iic_delay(); |
} while (b >>= 1); |
SDA_HIGH(); |
iic_delay(); |
SCL_HIGH(); |
ack = SDA_VAL ? FALSE : TRUE; /* Sample ACK */ |
iic_delay(); |
SCL_LOW(); |
iic_delay(); |
return ack; |
} |
/* Receive a byte from the IIC bus */ |
static |
BYTE iic_rcvr (BOOL ack) |
{ |
UINT d = 1; |
do { |
d <<= 1; |
SCL_HIGH(); |
if (SDA_VAL) d++; |
iic_delay(); |
SCL_LOW(); |
iic_delay(); |
} while (d < 0x100); |
if (ack) { /* SDA = ACK */ |
SDA_LOW(); |
} else { |
SDA_HIGH(); |
} |
iic_delay(); |
SCL_HIGH(); |
iic_delay(); |
SCL_LOW(); |
SDA_HIGH(); |
iic_delay(); |
return (BYTE)d; |
} |
BOOL rtc_read ( |
UINT adr, /* Read start address */ |
UINT cnt, /* Read byte count */ |
void* buff /* Read data buffer */ |
) |
{ |
BYTE *rbuff = buff; |
int n; |
if (!cnt) return FALSE; |
n = 10; |
do { /* Select DS1338 (0xD0) */ |
iic_start(); |
} while (!iic_send(0xD0) && --n); |
if (!n) return FALSE; |
if (iic_send((BYTE)adr)) { /* Set start address */ |
iic_start(); /* Reselect DS1338 in read mode (0xD1) */ |
if (iic_send(0xD1)) { |
do { /* Receive data */ |
cnt--; |
*rbuff++ = iic_rcvr(cnt ? TRUE : FALSE); |
} while (cnt); |
} |
} |
iic_stop(); /* Deselect device */ |
return cnt ? FALSE : TRUE; |
} |
BOOL rtc_write ( |
UINT adr, /* Write start address */ |
UINT cnt, /* Write byte count */ |
const void* buff /* Data to be written */ |
) |
{ |
const BYTE *wbuff = buff; |
int n; |
if (!cnt) return FALSE; |
n = 10; |
do { /* Select DS1338 (0xD0) */ |
iic_start(); |
} while (!iic_send(0xD0) && --n); |
if (!n) return FALSE; |
if (iic_send((BYTE)adr)) { /* Set start address */ |
do { /* Send data */ |
if (!iic_send(*wbuff++)) break; |
} while (--cnt); |
} |
iic_stop(); /* Deselect device */ |
return cnt ? FALSE : TRUE; |
} |
BOOL rtc_gettime (RTC *rtc) |
{ |
BYTE buf[8]; |
if (!rtc_read(0, 7, buf)) return FALSE; |
rtc->sec = (buf[0] & 0x0F) + ((buf[0] >> 4) & 7) * 10; |
rtc->min = (buf[1] & 0x0F) + (buf[1] >> 4) * 10; |
rtc->hour = (buf[2] & 0x0F) + ((buf[2] >> 4) & 3) * 10; |
rtc->mday = (buf[4] & 0x0F) + ((buf[4] >> 4) & 3) * 10; |
rtc->month = (buf[5] & 0x0F) + ((buf[5] >> 4) & 1) * 10; |
rtc->year = 2000 + (buf[6] & 0x0F) + (buf[6] >> 4) * 10; |
return TRUE; |
} |
BOOL rtc_settime (const RTC *rtc) |
{ |
BYTE buf[8]; |
buf[0] = rtc->sec / 10 * 16 + rtc->sec % 10; |
buf[1] = rtc->min / 10 * 16 + rtc->min % 10; |
buf[2] = rtc->hour / 10 * 16 + rtc->hour % 10; |
buf[3] = 0; |
buf[4] = rtc->mday / 10 * 16 + rtc->mday % 10; |
buf[5] = rtc->month / 10 * 16 + rtc->month % 10; |
buf[6] = (rtc->year - 2000) / 10 * 16 + (rtc->year - 2000) % 10; |
rtc_write(0, 7, buf); |
return TRUE; |
} |
BOOL rtc_init (void) |
{ |
BYTE buf[8]; /* RTC R/W buffer */ |
UINT n; |
/* Read RTC registers */ |
if (!rtc_read(0, 8, buf)) return FALSE; /* IIC error */ |
if (buf[7] & 0x20) { /* When RTC data has been broken, set default time */ |
/* Reset time to Jan 1, '08 */ |
memset(buf, 0, 8); |
buf[4] = 1; buf[5] = 1; buf[6] = 8; |
rtc_write(0, 8, buf); |
/* Clear data memory */ |
memset(buf, 0, 8); |
for (n = 8; n < 64; n += 8) |
rtc_write(n, 8, buf); |
return FALSE; |
} |
return TRUE; |
} |
/programy/C/avr/SDcard/rtc.h |
---|
0,0 → 1,18 |
#include "integer.h" |
#include "rtc.c" |
typedef struct { |
WORD year; |
BYTE month; |
BYTE mday; |
BYTE hour; |
BYTE min; |
BYTE sec; |
} RTC; |
BOOL rtc_init (void); /* Initialize RTC */ |
BOOL rtc_gettime (RTC*); /* Get time */ |
BOOL rtc_settime (const RTC*); /* Set time */ |
BOOL rtc_write (UINT, UINT, const void*); /* Write RTC regs */ |
BOOL rtc_read (UINT, UINT, void*); /* Read RTC regs */ |
/programy/C/avr/SDcard/tff.c |
---|
0,0 → 1,1876 |
/*----------------------------------------------------------------------------/ |
/ FatFs - Tiny FAT file system module R0.06 (C)ChaN, 2008 |
/-----------------------------------------------------------------------------/ |
/ The FatFs module is an experimenal project to implement FAT file system to |
/ cheap microcontrollers. This is a free software and is opened for education, |
/ research and development under license policy of following trems. |
/ |
/ Copyright (C) 2008, ChaN, all right reserved. |
/ |
/ * The FatFs module is a free software and there is no warranty. |
/ * You can use, modify and/or redistribute it for personal, non-profit or |
/ commercial use without any restriction under your responsibility. |
/ * Redistributions of source code must retain the above copyright notice. |
/ |
/-----------------------------------------------------------------------------/ |
/ Feb 26,'06 R0.00 Prototype. |
/ |
/ Apr 29,'06 R0.01 First stable version. |
/ |
/ Jun 01,'06 R0.02 Added FAT12 support. |
/ Removed unbuffered mode. |
/ Fixed a problem on small (<32M) patition. |
/ Jun 10,'06 R0.02a Added a configuration option (_FS_MINIMUM). |
/ |
/ Sep 22,'06 R0.03 Added f_rename(). |
/ Changed option _FS_MINIMUM to _FS_MINIMIZE. |
/ Dec 09,'06 R0.03a Improved cluster scan algolithm to write files fast. |
/ |
/ Feb 04,'07 R0.04 Added FAT32 supprt. |
/ Changed some interfaces incidental to FatFs. |
/ Changed f_mountdrv() to f_mount(). |
/ Apr 01,'07 R0.04a Added a capability of extending file size to f_lseek(). |
/ Added minimization level 3. |
/ Fixed a problem in FAT32 support. |
/ May 05,'07 R0.04b Added a configuration option _USE_NTFLAG. |
/ Added FSInfo support. |
/ Fixed some problems corresponds to FAT32 support. |
/ Fixed DBCS name can result FR_INVALID_NAME. |
/ Fixed short seek (<= csize) collapses the file object. |
/ |
/ Aug 25,'07 R0.05 Changed arguments of f_read() and f_write(). |
/ Feb 03,'08 R0.05a Added f_truncate() and f_utime(). |
/ Fixed off by one error at FAT sub-type determination. |
/ Fixed btr in f_read() can be mistruncated. |
/ Fixed cached sector is not flushed when create and close |
/ without write. |
/ |
/ Apr 01,'08 R0.06 Added f_forward(), fputc(), fputs(), fprintf() and fgets(). |
/ Improved performance of f_lseek() on moving to the same |
/ or following cluster. |
/----------------------------------------------------------------------------*/ |
#include <string.h> |
#include "tff.h" /* Tiny-FatFs declarations */ |
#include "diskio.h" /* Include file for user provided disk functions */ |
static |
FATFS *FatFs; /* Pointer to the file system objects (logical drive) */ |
static |
WORD fsid; /* File system mount ID */ |
/*------------------------------------------------------------------------- |
Module Private Functions |
-------------------------------------------------------------------------*/ |
/*-----------------------------------------------------------------------*/ |
/* Change window offset */ |
/*-----------------------------------------------------------------------*/ |
static |
BOOL move_window ( /* TRUE: successful, FALSE: failed */ |
DWORD sector /* Sector number to make apperance in the FatFs->win */ |
) /* Move to zero only writes back dirty window */ |
{ |
DWORD wsect; |
FATFS *fs = FatFs; |
wsect = fs->winsect; |
if (wsect != sector) { /* Changed current window */ |
#if !_FS_READONLY |
BYTE n; |
if (fs->winflag) { /* Write back dirty window if needed */ |
if (disk_write(0, fs->win, wsect, 1) != RES_OK) |
return FALSE; |
fs->winflag = 0; |
if (wsect < (fs->fatbase + fs->sects_fat)) { /* In FAT area */ |
for (n = fs->n_fats; n >= 2; n--) { /* Refrect the change to all FAT copies */ |
wsect += fs->sects_fat; |
disk_write(0, fs->win, wsect, 1); |
} |
} |
} |
#endif |
if (sector) { |
if (disk_read(0, fs->win, sector, 1) != RES_OK) |
return FALSE; |
fs->winsect = sector; |
} |
} |
return TRUE; |
} |
/*-----------------------------------------------------------------------*/ |
/* Clean-up cached data */ |
/*-----------------------------------------------------------------------*/ |
#if !_FS_READONLY |
static |
FRESULT sync (void) /* FR_OK: successful, FR_RW_ERROR: failed */ |
{ |
FATFS *fs = FatFs; |
fs->winflag = 1; |
if (!move_window(0)) return FR_RW_ERROR; |
#if _USE_FSINFO |
/* Update FSInfo sector if needed */ |
if (fs->fs_type == FS_FAT32 && fs->fsi_flag) { |
fs->winsect = 0; |
memset(fs->win, 0, 512U); |
ST_WORD(&fs->win[BS_55AA], 0xAA55); |
ST_DWORD(&fs->win[FSI_LeadSig], 0x41615252); |
ST_DWORD(&fs->win[FSI_StrucSig], 0x61417272); |
ST_DWORD(&fs->win[FSI_Free_Count], fs->free_clust); |
ST_DWORD(&fs->win[FSI_Nxt_Free], fs->last_clust); |
disk_write(0, fs->win, fs->fsi_sector, 1); |
fs->fsi_flag = 0; |
} |
#endif |
/* Make sure that no pending write process in the physical drive */ |
if (disk_ioctl(0, CTRL_SYNC, NULL) != RES_OK) |
return FR_RW_ERROR; |
return FR_OK; |
} |
#endif |
/*-----------------------------------------------------------------------*/ |
/* Get a cluster status */ |
/*-----------------------------------------------------------------------*/ |
static |
CLUST get_cluster ( /* 0,>=2: successful, 1: failed */ |
CLUST clust /* Cluster# to get the link information */ |
) |
{ |
WORD wc, bc; |
DWORD fatsect; |
FATFS *fs = FatFs; |
if (clust >= 2 && clust < fs->max_clust) { /* Valid cluster# */ |
fatsect = fs->fatbase; |
switch (fs->fs_type) { |
case FS_FAT12 : |
bc = (WORD)clust * 3 / 2; |
if (!move_window(fatsect + bc / 512U)) break; |
wc = fs->win[bc % 512U]; bc++; |
if (!move_window(fatsect + bc / 512U)) break; |
wc |= (WORD)fs->win[bc % 512U] << 8; |
return (clust & 1) ? (wc >> 4) : (wc & 0xFFF); |
case FS_FAT16 : |
if (!move_window(fatsect + clust / 256)) break; |
return LD_WORD(&fs->win[((WORD)clust * 2) % 512U]); |
#if _FAT32 |
case FS_FAT32 : |
if (!move_window(fatsect + clust / 128)) break; |
return LD_DWORD(&fs->win[((WORD)clust * 4) % 512U]) & 0x0FFFFFFF; |
#endif |
} |
} |
return 1; /* Out of cluster range, or an error occured */ |
} |
/*-----------------------------------------------------------------------*/ |
/* Change a cluster status */ |
/*-----------------------------------------------------------------------*/ |
#if !_FS_READONLY |
static |
BOOL put_cluster ( /* TRUE: successful, FALSE: failed */ |
CLUST clust, /* Cluster# to change (must be 2 to fs->max_clust-1) */ |
CLUST val /* New value to mark the cluster */ |
) |
{ |
WORD bc; |
BYTE *p; |
DWORD fatsect; |
FATFS *fs = FatFs; |
fatsect = fs->fatbase; |
switch (fs->fs_type) { |
case FS_FAT12 : |
bc = (WORD)clust * 3 / 2; |
if (!move_window(fatsect + bc / 512U)) return FALSE; |
p = &fs->win[bc % 512U]; |
*p = (clust & 1) ? ((*p & 0x0F) | ((BYTE)val << 4)) : (BYTE)val; |
bc++; |
fs->winflag = 1; |
if (!move_window(fatsect + bc / 512U)) return FALSE; |
p = &fs->win[bc % 512U]; |
*p = (clust & 1) ? (BYTE)(val >> 4) : ((*p & 0xF0) | ((BYTE)(val >> 8) & 0x0F)); |
break; |
case FS_FAT16 : |
if (!move_window(fatsect + clust / 256)) return FALSE; |
ST_WORD(&fs->win[((WORD)clust * 2) % 512U], (WORD)val); |
break; |
#if _FAT32 |
case FS_FAT32 : |
if (!move_window(fatsect + clust / 128)) return FALSE; |
ST_DWORD(&fs->win[((WORD)clust * 4) % 512U], val); |
break; |
#endif |
default : |
return FALSE; |
} |
fs->winflag = 1; |
return TRUE; |
} |
#endif /* !_FS_READONLY */ |
/*-----------------------------------------------------------------------*/ |
/* Remove a cluster chain */ |
/*-----------------------------------------------------------------------*/ |
#if !_FS_READONLY |
static |
BOOL remove_chain ( /* TRUE: successful, FALSE: failed */ |
CLUST clust /* Cluster# to remove chain from */ |
) |
{ |
CLUST nxt; |
FATFS *fs = FatFs; |
while (clust >= 2 && clust < fs->max_clust) { |
nxt = get_cluster(clust); |
if (nxt == 1) return FALSE; |
if (!put_cluster(clust, 0)) return FALSE; |
if (fs->free_clust != (CLUST)0xFFFFFFFF) { |
fs->free_clust++; |
#if _USE_FSINFO |
fs->fsi_flag = 1; |
#endif |
} |
clust = nxt; |
} |
return TRUE; |
} |
#endif |
/*-----------------------------------------------------------------------*/ |
/* Stretch or create a cluster chain */ |
/*-----------------------------------------------------------------------*/ |
#if !_FS_READONLY |
static |
CLUST create_chain ( /* 0: No free cluster, 1: Error, >=2: New cluster number */ |
CLUST clust /* Cluster# to stretch, 0 means create new */ |
) |
{ |
CLUST cstat, ncl, scl, mcl; |
FATFS *fs = FatFs; |
mcl = fs->max_clust; |
if (clust == 0) { /* Create new chain */ |
scl = fs->last_clust; /* Get last allocated cluster */ |
if (scl < 2 || scl >= mcl) scl = 1; |
} |
else { /* Stretch existing chain */ |
cstat = get_cluster(clust); /* Check the cluster status */ |
if (cstat < 2) return 1; /* It is an invalid cluster */ |
if (cstat < mcl) return cstat; /* It is already followed by next cluster */ |
scl = clust; |
} |
ncl = scl; /* Start cluster */ |
for (;;) { |
ncl++; /* Next cluster */ |
if (ncl >= mcl) { /* Wrap around */ |
ncl = 2; |
if (ncl > scl) return 0; /* No free custer */ |
} |
cstat = get_cluster(ncl); /* Get the cluster status */ |
if (cstat == 0) break; /* Found a free cluster */ |
if (cstat == 1) return 1; /* Any error occured */ |
if (ncl == scl) return 0; /* No free custer */ |
} |
if (!put_cluster(ncl, (CLUST)0x0FFFFFFF)) return 1; /* Mark the new cluster "in use" */ |
if (clust != 0 && !put_cluster(clust, ncl)) return 1; /* Link it to previous one if needed */ |
fs->last_clust = ncl; /* Update fsinfo */ |
if (fs->free_clust != (CLUST)0xFFFFFFFF) { |
fs->free_clust--; |
#if _USE_FSINFO |
fs->fsi_flag = 1; |
#endif |
} |
return ncl; /* Return new cluster number */ |
} |
#endif /* !_FS_READONLY */ |
/*-----------------------------------------------------------------------*/ |
/* Get sector# from cluster# */ |
/*-----------------------------------------------------------------------*/ |
static |
DWORD clust2sect ( /* !=0: sector number, 0: failed - invalid cluster# */ |
CLUST clust /* Cluster# to be converted */ |
) |
{ |
FATFS *fs = FatFs; |
clust -= 2; |
if (clust >= (fs->max_clust - 2)) return 0; /* Invalid cluster# */ |
return (DWORD)clust * fs->csize + fs->database; |
} |
/*-----------------------------------------------------------------------*/ |
/* Move directory pointer to next */ |
/*-----------------------------------------------------------------------*/ |
static |
BOOL next_dir_entry ( /* TRUE: successful, FALSE: could not move next */ |
DIR *dj /* Pointer to directory object */ |
) |
{ |
CLUST clust; |
WORD idx; |
idx = dj->index + 1; |
if ((idx & 15) == 0) { /* Table sector changed? */ |
dj->sect++; /* Next sector */ |
if (dj->clust == 0) { /* In static table */ |
if (idx >= dj->fs->n_rootdir) return FALSE; /* Reached to end of table */ |
} else { /* In dynamic table */ |
if (((idx / 16) & (dj->fs->csize - 1)) == 0) { /* Cluster changed? */ |
clust = get_cluster(dj->clust); /* Get next cluster */ |
if (clust < 2 || clust >= dj->fs->max_clust) /* Reached to end of table */ |
return FALSE; |
dj->clust = clust; /* Initialize for new cluster */ |
dj->sect = clust2sect(clust); |
} |
} |
} |
dj->index = idx; /* Lower 4 bit of dj->index indicates offset in dj->sect */ |
return TRUE; |
} |
/*-----------------------------------------------------------------------*/ |
/* Get file status from directory entry */ |
/*-----------------------------------------------------------------------*/ |
#if _FS_MINIMIZE <= 1 |
static |
void get_fileinfo ( /* No return code */ |
FILINFO *finfo, /* Ptr to store the File Information */ |
const BYTE *dir /* Ptr to the directory entry */ |
) |
{ |
BYTE n, c, a; |
char *p; |
p = &finfo->fname[0]; |
a = _USE_NTFLAG ? dir[DIR_NTres] : 0; /* NT flag */ |
for (n = 0; n < 8; n++) { /* Convert file name (body) */ |
c = dir[n]; |
if (c == ' ') break; |
if (c == 0x05) c = 0xE5; |
if (a & 0x08 && c >= 'A' && c <= 'Z') c += 0x20; |
*p++ = c; |
} |
if (dir[8] != ' ') { /* Convert file name (extension) */ |
*p++ = '.'; |
for (n = 8; n < 11; n++) { |
c = dir[n]; |
if (c == ' ') break; |
if (a & 0x10 && c >= 'A' && c <= 'Z') c += 0x20; |
*p++ = c; |
} |
} |
*p = '\0'; |
finfo->fattrib = dir[DIR_Attr]; /* Attribute */ |
finfo->fsize = LD_DWORD(&dir[DIR_FileSize]); /* Size */ |
finfo->fdate = LD_WORD(&dir[DIR_WrtDate]); /* Date */ |
finfo->ftime = LD_WORD(&dir[DIR_WrtTime]); /* Time */ |
} |
#endif /* _FS_MINIMIZE <= 1 */ |
/*-----------------------------------------------------------------------*/ |
/* Pick a paragraph and create the name in format of directory entry */ |
/*-----------------------------------------------------------------------*/ |
static |
char make_dirfile ( /* 1: error - detected an invalid format, '\0'or'/': next character */ |
const char **path, /* Pointer to the file path pointer */ |
char *dirname /* Pointer to directory name buffer {Name(8), Ext(3), NT flag(1)} */ |
) |
{ |
BYTE n, t, c, a, b; |
memset(dirname, ' ', 8+3); /* Fill buffer with spaces */ |
a = 0; b = 0x18; /* NT flag */ |
n = 0; t = 8; |
for (;;) { |
c = *(*path)++; |
if (c == '\0' || c == '/') { /* Reached to end of str or directory separator */ |
if (n == 0) break; |
dirname[11] = _USE_NTFLAG ? (a & b) : 0; |
return c; |
} |
if (c <= ' ' || c == 0x7F) break; /* Reject invisible chars */ |
if (c == '.') { |
if (!(a & 1) && n >= 1 && n <= 8) { /* Enter extension part */ |
n = 8; t = 11; continue; |
} |
break; |
} |
if (_USE_SJIS && |
((c >= 0x81 && c <= 0x9F) || /* Accept S-JIS code */ |
(c >= 0xE0 && c <= 0xFC))) { |
if (n == 0 && c == 0xE5) /* Change heading \xE5 to \x05 */ |
c = 0x05; |
a ^= 1; goto md_l2; |
} |
if (c == '"') break; /* Reject " */ |
if (c <= ')') goto md_l1; /* Accept ! # $ % & ' ( ) */ |
if (c <= ',') break; /* Reject * + , */ |
if (c <= '9') goto md_l1; /* Accept - 0-9 */ |
if (c <= '?') break; /* Reject : ; < = > ? */ |
if (!(a & 1)) { /* These checks are not applied to S-JIS 2nd byte */ |
if (c == '|') break; /* Reject | */ |
if (c >= '[' && c <= ']') break;/* Reject [ \ ] */ |
if (_USE_NTFLAG && c >= 'A' && c <= 'Z') |
(t == 8) ? (b &= 0xF7) : (b &= 0xEF); |
if (c >= 'a' && c <= 'z') { /* Convert to upper case */ |
c -= 0x20; |
if (_USE_NTFLAG) (t == 8) ? (a |= 0x08) : (a |= 0x10); |
} |
} |
md_l1: |
a &= 0xFE; |
md_l2: |
if (n >= t) break; |
dirname[n++] = c; |
} |
return 1; |
} |
/*-----------------------------------------------------------------------*/ |
/* Trace a file path */ |
/*-----------------------------------------------------------------------*/ |
static |
FRESULT trace_path ( /* FR_OK(0): successful, !=0: error code */ |
DIR *dj, /* Pointer to directory object to return last directory */ |
char *fn, /* Pointer to last segment name to return */ |
const char *path, /* Full-path string to trace a file or directory */ |
BYTE **dir /* Pointer to pointer to found entry to retutn */ |
) |
{ |
CLUST clust; |
char ds; |
BYTE *dptr = NULL; |
FATFS *fs = FatFs; |
/* Initialize directory object */ |
dj->fs = fs; |
clust = fs->dirbase; |
#if _FAT32 |
if (fs->fs_type == FS_FAT32) { |
dj->clust = dj->sclust = clust; |
dj->sect = clust2sect(clust); |
} else |
#endif |
{ |
dj->clust = dj->sclust = 0; |
dj->sect = clust; |
} |
dj->index = 0; |
if (*path == '\0') { /* Null path means the root directory */ |
*dir = NULL; return FR_OK; |
} |
for (;;) { |
ds = make_dirfile(&path, fn); /* Get a paragraph into fn[] */ |
if (ds == 1) return FR_INVALID_NAME; |
for (;;) { |
if (!move_window(dj->sect)) return FR_RW_ERROR; |
dptr = &fs->win[(dj->index & 15) * 32]; /* Pointer to the directory entry */ |
if (dptr[DIR_Name] == 0) /* Has it reached to end of dir? */ |
return !ds ? FR_NO_FILE : FR_NO_PATH; |
if (dptr[DIR_Name] != 0xE5 /* Matched? */ |
&& !(dptr[DIR_Attr] & AM_VOL) |
&& !memcmp(&dptr[DIR_Name], fn, 8+3) ) break; |
if (!next_dir_entry(dj)) /* Next directory pointer */ |
return !ds ? FR_NO_FILE : FR_NO_PATH; |
} |
if (!ds) { *dir = dptr; return FR_OK; } /* Matched with end of path */ |
if (!(dptr[DIR_Attr] & AM_DIR)) return FR_NO_PATH; /* Cannot trace because it is a file */ |
clust = /* Get cluster# of the directory */ |
#if _FAT32 |
((DWORD)LD_WORD(&dptr[DIR_FstClusHI]) << 16) | |
#endif |
LD_WORD(&dptr[DIR_FstClusLO]); |
dj->clust = dj->sclust = clust; /* Restart scannig with the new directory */ |
dj->sect = clust2sect(clust); |
dj->index = 2; |
} |
} |
/*-----------------------------------------------------------------------*/ |
/* Reserve a directory entry */ |
/*-----------------------------------------------------------------------*/ |
#if !_FS_READONLY |
static |
FRESULT reserve_direntry ( /* FR_OK: successful, FR_DENIED: no free entry, FR_RW_ERROR: a disk error occured */ |
DIR *dj, /* Target directory to create new entry */ |
BYTE **dir /* Pointer to pointer to created entry to retutn */ |
) |
{ |
CLUST clust; |
DWORD sector; |
BYTE c, n, *dptr; |
FATFS *fs = dj->fs; |
/* Re-initialize directory object */ |
clust = dj->sclust; |
if (clust != 0) { /* Dyanmic directory table */ |
dj->clust = clust; |
dj->sect = clust2sect(clust); |
} else { /* Static directory table */ |
dj->sect = fs->dirbase; |
} |
dj->index = 0; |
do { |
if (!move_window(dj->sect)) return FR_RW_ERROR; |
dptr = &fs->win[(dj->index & 15) * 32]; /* Pointer to the directory entry */ |
c = dptr[DIR_Name]; |
if (c == 0 || c == 0xE5) { /* Found an empty entry! */ |
*dir = dptr; return FR_OK; |
} |
} while (next_dir_entry(dj)); /* Next directory pointer */ |
/* Reached to end of the directory table */ |
/* Abort when static table or could not stretch dynamic table */ |
if (clust == 0 || !(clust = create_chain(dj->clust))) return FR_DENIED; |
if (clust == 1 || !move_window(0)) return FR_RW_ERROR; |
fs->winsect = sector = clust2sect(clust); /* Cleanup the expanded table */ |
memset(fs->win, 0, 512U); |
for (n = fs->csize; n; n--) { |
if (disk_write(0, fs->win, sector, 1) != RES_OK) |
return FR_RW_ERROR; |
sector++; |
} |
fs->winflag = 1; |
*dir = fs->win; |
return FR_OK; |
} |
#endif /* !_FS_READONLY */ |
/*-----------------------------------------------------------------------*/ |
/* Load boot record and check if it is an FAT boot record */ |
/*-----------------------------------------------------------------------*/ |
static |
BYTE check_fs ( /* 0:The FAT boot record, 1:Valid boot record but not an FAT, 2:Not a boot record or error */ |
DWORD sect /* Sector# to check if it is an FAT boot record or not */ |
) |
{ |
FATFS *fs = FatFs; |
if (disk_read(0, fs->win, sect, 1) != RES_OK) /* Load boot record */ |
return 2; |
if (LD_WORD(&fs->win[BS_55AA]) != 0xAA55) /* Check record signature */ |
return 2; |
if (!memcmp(&fs->win[BS_FilSysType], "FAT", 3)) /* Check FAT signature */ |
return 0; |
#if _FAT32 |
if (!memcmp(&fs->win[BS_FilSysType32], "FAT32", 5) && !(fs->win[BPB_ExtFlags] & 0x80)) |
return 0; |
#endif |
return 1; |
} |
/*-----------------------------------------------------------------------*/ |
/* Make sure that the file system is valid */ |
/*-----------------------------------------------------------------------*/ |
static |
FRESULT auto_mount ( /* FR_OK(0): successful, !=0: any error occured */ |
const char **path, /* Pointer to pointer to the path name (drive number) */ |
BYTE chk_wp /* !=0: Check media write protection for write access */ |
) |
{ |
BYTE fmt; |
DSTATUS stat; |
DWORD bootsect, fatsize, totalsect, maxclust; |
const char *p = *path; |
FATFS *fs; |
while (*p == ' ') p++; /* Strip leading spaces */ |
if (*p == '/') p++; /* Strip heading slash */ |
*path = p; /* Return pointer to the path name */ |
/* Is the file system object registered? */ |
fs = FatFs; |
if (!fs) return FR_NOT_ENABLED; |
if (fs->fs_type) { /* If the logical drive has been mounted */ |
stat = disk_status(0); |
if (!(stat & STA_NOINIT)) { /* and physical drive is kept initialized (has not been changed), */ |
#if !_FS_READONLY |
if (chk_wp && (stat & STA_PROTECT)) /* Check write protection if needed */ |
return FR_WRITE_PROTECTED; |
#endif |
return FR_OK; /* The file system object is valid */ |
} |
} |
/* The logical drive must be re-mounted. Following code attempts to mount the logical drive */ |
memset(fs, 0, sizeof(FATFS)); /* Clean-up the file system object */ |
stat = disk_initialize(0); /* Initialize low level disk I/O layer */ |
if (stat & STA_NOINIT) /* Check if the drive is ready */ |
return FR_NOT_READY; |
#if !_FS_READONLY |
if (chk_wp && (stat & STA_PROTECT)) /* Check write protection if needed */ |
return FR_WRITE_PROTECTED; |
#endif |
/* Search FAT partition on the drive */ |
fmt = check_fs(bootsect = 0); /* Check sector 0 as an SFD format */ |
if (fmt == 1) { /* Not an FAT boot record, it may be patitioned */ |
/* Check a partition listed in top of the partition table */ |
if (fs->win[MBR_Table+4]) { /* Is the 1st partition existing? */ |
bootsect = LD_DWORD(&fs->win[MBR_Table+8]); /* Partition offset in LBA */ |
fmt = check_fs(bootsect); /* Check the partition */ |
} |
} |
if (fmt || LD_WORD(&fs->win[BPB_BytsPerSec]) != 512U) /* No valid FAT patition is found */ |
return FR_NO_FILESYSTEM; |
/* Initialize the file system object */ |
fatsize = LD_WORD(&fs->win[BPB_FATSz16]); /* Number of sectors per FAT */ |
if (!fatsize) fatsize = LD_DWORD(&fs->win[BPB_FATSz32]); |
fs->sects_fat = (CLUST)fatsize; |
fs->n_fats = fs->win[BPB_NumFATs]; /* Number of FAT copies */ |
fatsize *= fs->n_fats; /* (Number of sectors in FAT area) */ |
fs->fatbase = bootsect + LD_WORD(&fs->win[BPB_RsvdSecCnt]); /* FAT start sector (lba) */ |
fs->csize = fs->win[BPB_SecPerClus]; /* Number of sectors per cluster */ |
fs->n_rootdir = LD_WORD(&fs->win[BPB_RootEntCnt]); /* Nmuber of root directory entries */ |
totalsect = LD_WORD(&fs->win[BPB_TotSec16]); /* Number of sectors on the file system */ |
if (!totalsect) totalsect = LD_DWORD(&fs->win[BPB_TotSec32]); |
fs->max_clust = maxclust = (totalsect /* max_clust = Last cluster# + 1 */ |
- LD_WORD(&fs->win[BPB_RsvdSecCnt]) - fatsize - fs->n_rootdir / 16 |
) / fs->csize + 2; |
fmt = FS_FAT12; /* Determine the FAT sub type */ |
if (maxclust >= 0xFF7) fmt = FS_FAT16; |
if (maxclust >= 0xFFF7) |
#if !_FAT32 |
return FR_NO_FILESYSTEM; |
#else |
fmt = FS_FAT32; |
if (fmt == FS_FAT32) |
fs->dirbase = LD_DWORD(&fs->win[BPB_RootClus]); /* Root directory start cluster */ |
else |
#endif |
fs->dirbase = fs->fatbase + fatsize; /* Root directory start sector (lba) */ |
fs->database = fs->fatbase + fatsize + fs->n_rootdir / 16; /* Data start sector (lba) */ |
#if !_FS_READONLY |
/* Initialize allocation information */ |
fs->free_clust = (CLUST)0xFFFFFFFF; |
#if _USE_FSINFO |
/* Get fsinfo if needed */ |
if (fmt == FS_FAT32) { |
fs->fsi_sector = bootsect + LD_WORD(&fs->win[BPB_FSInfo]); |
if (disk_read(0, fs->win, fs->fsi_sector, 1) == RES_OK && |
LD_WORD(&fs->win[BS_55AA]) == 0xAA55 && |
LD_DWORD(&fs->win[FSI_LeadSig]) == 0x41615252 && |
LD_DWORD(&fs->win[FSI_StrucSig]) == 0x61417272) { |
fs->last_clust = LD_DWORD(&fs->win[FSI_Nxt_Free]); |
fs->free_clust = LD_DWORD(&fs->win[FSI_Free_Count]); |
} |
} |
#endif |
#endif |
fs->fs_type = fmt; /* FAT syb-type */ |
fs->id = ++fsid; /* File system mount ID */ |
return FR_OK; |
} |
/*-----------------------------------------------------------------------*/ |
/* Check if the file/dir object is valid or not */ |
/*-----------------------------------------------------------------------*/ |
static |
FRESULT validate ( /* FR_OK(0): The object is valid, !=0: Invalid */ |
const FATFS *fs, /* Pointer to the file system object */ |
WORD id /* Member id of the target object to be checked */ |
) |
{ |
if (!fs || !fs->fs_type || fs->id != id) |
return FR_INVALID_OBJECT; |
if (disk_status(0) & STA_NOINIT) |
return FR_NOT_READY; |
return FR_OK; |
} |
/*-------------------------------------------------------------------------- |
Public Functions |
--------------------------------------------------------------------------*/ |
/*-----------------------------------------------------------------------*/ |
/* Mount/Unmount a Locical Drive */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_mount ( |
BYTE drv, /* Logical drive number to be mounted/unmounted */ |
FATFS *fs /* Pointer to new file system object (NULL for unmount)*/ |
) |
{ |
if (drv) return FR_INVALID_DRIVE; |
if (FatFs) FatFs->fs_type = 0; /* Clear old object */ |
FatFs = fs; /* Register and clear new object */ |
if (fs) fs->fs_type = 0; |
return FR_OK; |
} |
/*-----------------------------------------------------------------------*/ |
/* Open or Create a File */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_open ( |
FIL *fp, /* Pointer to the blank file object */ |
const char *path, /* Pointer to the file name */ |
BYTE mode /* Access mode and file open mode flags */ |
) |
{ |
FRESULT res; |
DIR dj; |
BYTE *dir; |
char fn[8+3+1]; |
fp->fs = NULL; /* Clear file object */ |
#if !_FS_READONLY |
mode &= (FA_READ|FA_WRITE|FA_CREATE_ALWAYS|FA_OPEN_ALWAYS|FA_CREATE_NEW); |
res = auto_mount(&path, (BYTE)(mode & (FA_WRITE|FA_CREATE_ALWAYS|FA_OPEN_ALWAYS|FA_CREATE_NEW))); |
#else |
mode &= FA_READ; |
res = auto_mount(&path, 0); |
#endif |
if (res != FR_OK) return res; |
res = trace_path(&dj, fn, path, &dir); /* Trace the file path */ |
#if !_FS_READONLY |
/* Create or Open a File */ |
if (mode & (FA_CREATE_ALWAYS|FA_OPEN_ALWAYS|FA_CREATE_NEW)) { |
CLUST rs; |
DWORD dw; |
if (res != FR_OK) { /* No file, create new */ |
if (res != FR_NO_FILE) return res; |
res = reserve_direntry(&dj, &dir); |
if (res != FR_OK) return res; |
memset(dir, 0, 32); /* Initialize the new entry with open name */ |
memcpy(&dir[DIR_Name], fn, 8+3); |
dir[DIR_NTres] = fn[11]; |
mode |= FA_CREATE_ALWAYS; |
} |
else { /* Any object is already existing */ |
if (mode & FA_CREATE_NEW) /* Cannot create new */ |
return FR_EXIST; |
if (!dir || (dir[DIR_Attr] & (AM_RDO|AM_DIR))) /* Cannot overwrite (R/O or DIR) */ |
return FR_DENIED; |
if (mode & FA_CREATE_ALWAYS) { /* Resize it to zero */ |
#if _FAT32 |
rs = ((DWORD)LD_WORD(&dir[DIR_FstClusHI]) << 16) | LD_WORD(&dir[DIR_FstClusLO]); |
ST_WORD(&dir[DIR_FstClusHI], 0); |
#else |
rs = LD_WORD(&dir[DIR_FstClusLO]); |
#endif |
ST_WORD(&dir[DIR_FstClusLO], 0); /* cluster = 0 */ |
ST_DWORD(&dir[DIR_FileSize], 0); /* size = 0 */ |
dj.fs->winflag = 1; |
dw = dj.fs->winsect; /* Remove the cluster chain */ |
if (!remove_chain(rs) || !move_window(dw)) |
return FR_RW_ERROR; |
dj.fs->last_clust = rs - 1; /* Reuse the cluster hole */ |
} |
} |
if (mode & FA_CREATE_ALWAYS) { |
dir[DIR_Attr] = 0; /* Reset attribute */ |
dw = get_fattime(); |
ST_DWORD(&dir[DIR_CrtTime], dw); /* Created time */ |
dj.fs->winflag = 1; |
mode |= FA__WRITTEN; /* Set file changed flag */ |
} |
} |
/* Open an existing file */ |
else { |
#endif /* !_FS_READONLY */ |
if (res != FR_OK) return res; /* Trace failed */ |
if (!dir || (dir[DIR_Attr] & AM_DIR)) /* It is a directory */ |
return FR_NO_FILE; |
#if !_FS_READONLY |
if ((mode & FA_WRITE) && (dir[DIR_Attr] & AM_RDO)) /* R/O violation */ |
return FR_DENIED; |
} |
fp->dir_sect = dj.fs->winsect; /* Pointer to the directory entry */ |
fp->dir_ptr = dir; |
#endif |
fp->flag = mode; /* File access mode */ |
fp->org_clust = /* File start cluster */ |
#if _FAT32 |
((DWORD)LD_WORD(&dir[DIR_FstClusHI]) << 16) | |
#endif |
LD_WORD(&dir[DIR_FstClusLO]); |
fp->fsize = LD_DWORD(&dir[DIR_FileSize]); /* File size */ |
fp->fptr = 0; fp->csect = 255; /* File pointer */ |
fp->fs = dj.fs; fp->id = dj.fs->id; /* Owner file system object of the file */ |
return FR_OK; |
} |
/*-----------------------------------------------------------------------*/ |
/* Read File */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_read ( |
FIL *fp, /* Pointer to the file object */ |
void *buff, /* Pointer to data buffer */ |
UINT btr, /* Number of bytes to read */ |
UINT *br /* Pointer to number of bytes read */ |
) |
{ |
FRESULT res; |
DWORD sect, remain; |
UINT rcnt, cc; |
CLUST clust; |
BYTE *rbuff = buff; |
*br = 0; |
res = validate(fp->fs, fp->id); /* Check validity of the object */ |
if (res != FR_OK) return res; |
if (fp->flag & FA__ERROR) return FR_RW_ERROR; /* Check error flag */ |
if (!(fp->flag & FA_READ)) return FR_DENIED; /* Check access mode */ |
remain = fp->fsize - fp->fptr; |
if (btr > remain) btr = (UINT)remain; /* Truncate btr by remaining bytes */ |
for ( ; btr; /* Repeat until all data transferred */ |
rbuff += rcnt, fp->fptr += rcnt, *br += rcnt, btr -= rcnt) { |
if ((fp->fptr % 512U) == 0) { /* On the sector boundary? */ |
if (fp->csect >= fp->fs->csize) { /* On the cluster boundary? */ |
clust = (fp->fptr == 0) ? /* On the top of the file? */ |
fp->org_clust : get_cluster(fp->curr_clust); |
if (clust < 2 || clust >= fp->fs->max_clust) goto fr_error; |
fp->curr_clust = clust; /* Update current cluster */ |
fp->csect = 0; /* Reset sector address in the cluster */ |
} |
sect = clust2sect(fp->curr_clust) + fp->csect; /* Get current sector */ |
cc = btr / 512U; /* When remaining bytes >= sector size, */ |
if (cc) { /* Read maximum contiguous sectors directly */ |
if (fp->csect + cc > fp->fs->csize) /* Clip at cluster boundary */ |
cc = fp->fs->csize - fp->csect; |
if (disk_read(0, rbuff, sect, (BYTE)cc) != RES_OK) |
goto fr_error; |
fp->csect += (BYTE)cc; /* Next sector address in the cluster */ |
rcnt = 512U * cc; /* Number of bytes transferred */ |
continue; |
} |
fp->csect++; /* Next sector address in the cluster */ |
} |
sect = clust2sect(fp->curr_clust) + fp->csect - 1; /* Get current sector */ |
if (!move_window(sect)) goto fr_error; /* Move sector window */ |
rcnt = 512U - (fp->fptr % 512U); /* Get partial sector from sector window */ |
if (rcnt > btr) rcnt = btr; |
memcpy(rbuff, &fp->fs->win[fp->fptr % 512U], rcnt); |
} |
return FR_OK; |
fr_error: /* Abort this file due to an unrecoverable error */ |
fp->flag |= FA__ERROR; |
return FR_RW_ERROR; |
} |
#if !_FS_READONLY |
/*-----------------------------------------------------------------------*/ |
/* Write File */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_write ( |
FIL *fp, /* Pointer to the file object */ |
const void *buff, /* Pointer to the data to be written */ |
UINT btw, /* Number of bytes to write */ |
UINT *bw /* Pointer to number of bytes written */ |
) |
{ |
FRESULT res; |
DWORD sect; |
UINT wcnt, cc; |
CLUST clust; |
const BYTE *wbuff = buff; |
*bw = 0; |
res = validate(fp->fs, fp->id); /* Check validity of the object */ |
if (res != FR_OK) return res; |
if (fp->flag & FA__ERROR) return FR_RW_ERROR; /* Check error flag */ |
if (!(fp->flag & FA_WRITE)) return FR_DENIED; /* Check access mode */ |
if (fp->fsize + btw < fp->fsize) return FR_OK; /* File size cannot reach 4GB */ |
for ( ; btw; /* Repeat until all data transferred */ |
wbuff += wcnt, fp->fptr += wcnt, *bw += wcnt, btw -= wcnt) { |
if ((fp->fptr % 512U) == 0) { /* On the sector boundary? */ |
if (fp->csect >= fp->fs->csize) { /* On the cluster boundary? */ |
if (fp->fptr == 0) { /* On the top of the file? */ |
clust = fp->org_clust; /* Follow from the origin */ |
if (clust == 0) /* When there is no cluster chain, */ |
fp->org_clust = clust = create_chain(0); /* Create a new cluster chain */ |
} else { /* Middle or end of the file */ |
clust = create_chain(fp->curr_clust); /* Trace or streach cluster chain */ |
} |
if (clust == 0) break; /* Could not allocate a new cluster (disk full) */ |
if (clust == 1 || clust >= fp->fs->max_clust) goto fw_error; |
fp->curr_clust = clust; /* Update current cluster */ |
fp->csect = 0; /* Reset sector address in the cluster */ |
} |
sect = clust2sect(fp->curr_clust) + fp->csect; /* Get current sector */ |
cc = btw / 512U; /* When remaining bytes >= sector size, */ |
if (cc) { /* Write maximum contiguous sectors directly */ |
if (fp->csect + cc > fp->fs->csize) /* Clip at cluster boundary */ |
cc = fp->fs->csize - fp->csect; |
if (disk_write(0, wbuff, sect, (BYTE)cc) != RES_OK) |
goto fw_error; |
fp->csect += (BYTE)cc; /* Next sector address in the cluster */ |
wcnt = 512U * cc; /* Number of bytes transferred */ |
continue; |
} |
if (fp->fptr >= fp->fsize) { /* Flush R/W window without reading if needed */ |
if (!move_window(0)) goto fw_error; |
fp->fs->winsect = sect; |
} |
fp->csect++; /* Next sector address in the cluster */ |
} |
sect = clust2sect(fp->curr_clust) + fp->csect - 1; /* Get current sector */ |
if (!move_window(sect)) goto fw_error; /* Move sector window */ |
wcnt = 512U - (fp->fptr % 512U); /* Put partial sector into sector window */ |
if (wcnt > btw) wcnt = btw; |
memcpy(&fp->fs->win[fp->fptr % 512U], wbuff, wcnt); |
fp->fs->winflag = 1; |
} |
if (fp->fptr > fp->fsize) fp->fsize = fp->fptr; /* Update file size if needed */ |
fp->flag |= FA__WRITTEN; /* Set file changed flag */ |
return res; |
fw_error: /* Abort this file due to an unrecoverable error */ |
fp->flag |= FA__ERROR; |
return FR_RW_ERROR; |
} |
/*-----------------------------------------------------------------------*/ |
/* Synchronize the file object */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_sync ( |
FIL *fp /* Pointer to the file object */ |
) |
{ |
FRESULT res; |
DWORD tim; |
BYTE *dir; |
res = validate(fp->fs, fp->id); /* Check validity of the object */ |
if (res == FR_OK) { |
if (fp->flag & FA__WRITTEN) { /* Has the file been written? */ |
/* Update the directory entry */ |
if (!move_window(fp->dir_sect)) |
return FR_RW_ERROR; |
dir = fp->dir_ptr; |
dir[DIR_Attr] |= AM_ARC; /* Set archive bit */ |
ST_DWORD(&dir[DIR_FileSize], fp->fsize); /* Update file size */ |
ST_WORD(&dir[DIR_FstClusLO], fp->org_clust); /* Update start cluster */ |
#if _FAT32 |
ST_WORD(&dir[DIR_FstClusHI], fp->org_clust >> 16); |
#endif |
tim = get_fattime(); /* Updated time */ |
ST_DWORD(&dir[DIR_WrtTime], tim); |
fp->flag &= (BYTE)~FA__WRITTEN; |
res = sync(); |
} |
} |
return res; |
} |
#endif /* !_FS_READONLY */ |
/*-----------------------------------------------------------------------*/ |
/* Close File */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_close ( |
FIL *fp /* Pointer to the file object to be closed */ |
) |
{ |
FRESULT res; |
#if !_FS_READONLY |
res = f_sync(fp); |
#else |
res = validate(fp->fs, fp->id); |
#endif |
if (res == FR_OK) fp->fs = NULL; |
return res; |
} |
#if _FS_MINIMIZE <= 2 |
/*-----------------------------------------------------------------------*/ |
/* Seek File R/W Pointer */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_lseek ( |
FIL *fp, /* Pointer to the file object */ |
DWORD ofs /* File pointer from top of file */ |
) |
{ |
FRESULT res; |
CLUST clust; |
DWORD csize, ifptr; |
res = validate(fp->fs, fp->id); /* Check validity of the object */ |
if (res != FR_OK) return res; |
if (fp->flag & FA__ERROR) return FR_RW_ERROR; |
if (ofs > fp->fsize /* In read-only mode, clip offset with the file size */ |
#if !_FS_READONLY |
&& !(fp->flag & FA_WRITE) |
#endif |
) ofs = fp->fsize; |
ifptr = fp->fptr; |
fp->fptr = 0; fp->csect = 255; |
if (ofs > 0) { |
csize = (DWORD)fp->fs->csize * 512U; /* Cluster size (byte) */ |
if (ifptr > 0 && |
(ofs - 1) / csize >= (ifptr - 1) / csize) {/* When seek to same or following cluster, */ |
fp->fptr = (ifptr - 1) & ~(csize - 1); /* start from the current cluster */ |
ofs -= fp->fptr; |
clust = fp->curr_clust; |
} else { /* When seek to back cluster, */ |
clust = fp->org_clust; /* start from the first cluster */ |
#if !_FS_READONLY |
if (clust == 0) { /* If no cluster chain, create a new chain */ |
clust = create_chain(0); |
if (clust == 1) goto fk_error; |
fp->org_clust = clust; |
} |
#endif |
fp->curr_clust = clust; |
} |
if (clust != 0) { |
while (ofs > csize) { /* Cluster following loop */ |
#if !_FS_READONLY |
if (fp->flag & FA_WRITE) { /* Check if in write mode or not */ |
clust = create_chain(clust); /* Force streached if in write mode */ |
if (clust == 0) { /* When disk gets full, clip file size */ |
ofs = csize; break; |
} |
} else |
#endif |
clust = get_cluster(clust); /* Follow cluster chain if not in write mode */ |
if (clust < 2 || clust >= fp->fs->max_clust) goto fk_error; |
fp->curr_clust = clust; |
fp->fptr += csize; |
ofs -= csize; |
} |
fp->fptr += ofs; |
fp->csect = (BYTE)(ofs / 512U); /* Sector offset in the cluster */ |
if (ofs % 512U) fp->csect++; |
} |
} |
#if !_FS_READONLY |
if (fp->fptr > fp->fsize) { /* Set changed flag if the file was extended */ |
fp->fsize = fp->fptr; |
fp->flag |= FA__WRITTEN; |
} |
#endif |
return FR_OK; |
fk_error: /* Abort this file due to an unrecoverable error */ |
fp->flag |= FA__ERROR; |
return FR_RW_ERROR; |
} |
#if _FS_MINIMIZE <= 1 |
/*-----------------------------------------------------------------------*/ |
/* Create a directroy object */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_opendir ( |
DIR *dj, /* Pointer to directory object to create */ |
const char *path /* Pointer to the directory path */ |
) |
{ |
FRESULT res; |
BYTE *dir; |
char fn[8+3+1]; |
res = auto_mount(&path, 0); |
if (res == FR_OK) { |
res = trace_path(dj, fn, path, &dir); /* Trace the directory path */ |
if (res == FR_OK) { /* Trace completed */ |
if (dir) { /* It is not the root dir */ |
if (dir[DIR_Attr] & AM_DIR) { /* The entry is a directory */ |
dj->clust = |
#if _FAT32 |
((DWORD)LD_WORD(&dir[DIR_FstClusHI]) << 16) | |
#endif |
LD_WORD(&dir[DIR_FstClusLO]); |
dj->sect = clust2sect(dj->clust); |
dj->index = 2; |
} else { /* The entry is not a directory */ |
res = FR_NO_FILE; |
} |
} |
dj->id = dj->fs->id; |
} |
} |
return res; |
} |
/*-----------------------------------------------------------------------*/ |
/* Read Directory Entry in Sequense */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_readdir ( |
DIR *dj, /* Pointer to the directory object */ |
FILINFO *finfo /* Pointer to file information to return */ |
) |
{ |
FRESULT res; |
BYTE *dir, c; |
res = validate(dj->fs, dj->id); /* Check validity of the object */ |
if (res != FR_OK) return res; |
finfo->fname[0] = 0; |
while (dj->sect) { |
if (!move_window(dj->sect)) |
return FR_RW_ERROR; |
dir = &dj->fs->win[(dj->index & 15) * 32]; /* pointer to the directory entry */ |
c = dir[DIR_Name]; |
if (c == 0) break; /* Has it reached to end of dir? */ |
if (c != 0xE5 && !(dir[DIR_Attr] & AM_VOL)) /* Is it a valid entry? */ |
get_fileinfo(finfo, dir); |
if (!next_dir_entry(dj)) dj->sect = 0; /* Next entry */ |
if (finfo->fname[0]) break; /* Found valid entry */ |
} |
return FR_OK; |
} |
#if _FS_MINIMIZE == 0 |
/*-----------------------------------------------------------------------*/ |
/* Get File Status */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_stat ( |
const char *path, /* Pointer to the file path */ |
FILINFO *finfo /* Pointer to file information to return */ |
) |
{ |
FRESULT res; |
DIR dj; |
BYTE *dir; |
char fn[8+3+1]; |
res = auto_mount(&path, 0); |
if (res == FR_OK) { |
res = trace_path(&dj, fn, path, &dir); /* Trace the file path */ |
if (res == FR_OK) { /* Trace completed */ |
if (dir) /* Found an object */ |
get_fileinfo(finfo, dir); |
else /* It is root dir */ |
res = FR_INVALID_NAME; |
} |
} |
return res; |
} |
#if !_FS_READONLY |
/*-----------------------------------------------------------------------*/ |
/* Truncate File */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_truncate ( |
FIL *fp /* Pointer to the file object */ |
) |
{ |
FRESULT res; |
CLUST ncl; |
res = validate(fp->fs, fp->id); /* Check validity of the object */ |
if (res != FR_OK) return res; |
if (fp->flag & FA__ERROR) return FR_RW_ERROR; /* Check error flag */ |
if (!(fp->flag & FA_WRITE)) return FR_DENIED; /* Check access mode */ |
if (fp->fsize > fp->fptr) { |
fp->fsize = fp->fptr; /* Set file size to current R/W point */ |
fp->flag |= FA__WRITTEN; |
if (fp->fptr == 0) { /* When set file size to zero, remove entire cluster chain */ |
if (!remove_chain(fp->org_clust)) goto ft_error; |
fp->org_clust = 0; |
} else { /* When truncate a part of the file, remove remaining clusters */ |
ncl = get_cluster(fp->curr_clust); |
if (ncl < 2) goto ft_error; |
if (ncl < fp->fs->max_clust) { |
if (!put_cluster(fp->curr_clust, (CLUST)0x0FFFFFFF)) goto ft_error; |
if (!remove_chain(ncl)) goto ft_error; |
} |
} |
} |
return FR_OK; |
ft_error: /* Abort this file due to an unrecoverable error */ |
fp->flag |= FA__ERROR; |
return FR_RW_ERROR; |
} |
/*-----------------------------------------------------------------------*/ |
/* Get Number of Free Clusters */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_getfree ( |
const char *drv, /* Pointer to the logical drive number (root dir) */ |
DWORD *nclust, /* Pointer to the variable to return number of free clusters */ |
FATFS **fatfs /* Pointer to pointer to corresponding file system object to return */ |
) |
{ |
FRESULT res; |
FATFS *fs; |
DWORD n, sect; |
CLUST clust; |
BYTE fat, f, *p; |
/* Get drive number */ |
res = auto_mount(&drv, 0); |
if (res != FR_OK) return res; |
*fatfs = fs = FatFs; |
/* If number of free cluster is valid, return it without cluster scan. */ |
if (fs->free_clust <= fs->max_clust - 2) { |
*nclust = fs->free_clust; |
return FR_OK; |
} |
/* Get number of free clusters */ |
fat = fs->fs_type; |
n = 0; |
if (fat == FS_FAT12) { |
clust = 2; |
do { |
if ((WORD)get_cluster(clust) == 0) n++; |
} while (++clust < fs->max_clust); |
} else { |
clust = fs->max_clust; |
sect = fs->fatbase; |
f = 0; p = 0; |
do { |
if (!f) { |
if (!move_window(sect++)) return FR_RW_ERROR; |
p = fs->win; |
} |
if (!_FAT32 || fat == FS_FAT16) { |
if (LD_WORD(p) == 0) n++; |
p += 2; f += 1; |
} else { |
if (LD_DWORD(p) == 0) n++; |
p += 4; f += 2; |
} |
} while (--clust); |
} |
fs->free_clust = n; |
#if _USE_FSINFO |
if (fat == FS_FAT32) fs->fsi_flag = 1; |
#endif |
*nclust = n; |
return FR_OK; |
} |
/*-----------------------------------------------------------------------*/ |
/* Delete a File or Directory */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_unlink ( |
const char *path /* Pointer to the file or directory path */ |
) |
{ |
FRESULT res; |
DIR dj; |
BYTE *dir, *sdir; |
DWORD dsect; |
char fn[8+3+1]; |
CLUST dclust; |
res = auto_mount(&path, 1); |
if (res != FR_OK) return res; |
res = trace_path(&dj, fn, path, &dir); /* Trace the file path */ |
if (res != FR_OK) return res; /* Trace failed */ |
if (!dir) return FR_INVALID_NAME; /* It is the root directory */ |
if (dir[DIR_Attr] & AM_RDO) return FR_DENIED; /* It is a R/O object */ |
dsect = dj.fs->winsect; |
dclust = |
#if _FAT32 |
((DWORD)LD_WORD(&dir[DIR_FstClusHI]) << 16) | |
#endif |
LD_WORD(&dir[DIR_FstClusLO]); |
if (dir[DIR_Attr] & AM_DIR) { /* It is a sub-directory */ |
dj.clust = dclust; /* Check if the sub-dir is empty or not */ |
dj.sect = clust2sect(dclust); |
dj.index = 2; |
do { |
if (!move_window(dj.sect)) return FR_RW_ERROR; |
sdir = &dj.fs->win[(dj.index & 15) * 32]; |
if (sdir[DIR_Name] == 0) break; |
if (sdir[DIR_Name] != 0xE5 && !(sdir[DIR_Attr] & AM_VOL)) |
return FR_DENIED; /* The directory is not empty */ |
} while (next_dir_entry(&dj)); |
} |
if (!move_window(dsect)) return FR_RW_ERROR; /* Mark the directory entry 'deleted' */ |
dir[DIR_Name] = 0xE5; |
dj.fs->winflag = 1; |
if (!remove_chain(dclust)) return FR_RW_ERROR; /* Remove the cluster chain */ |
return sync(); |
} |
/*-----------------------------------------------------------------------*/ |
/* Create a Directory */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_mkdir ( |
const char *path /* Pointer to the directory path */ |
) |
{ |
FRESULT res; |
DIR dj; |
BYTE *dir, *fw, n; |
char fn[8+3+1]; |
DWORD sect, dsect, tim; |
CLUST dclust, pclust; |
res = auto_mount(&path, 1); |
if (res != FR_OK) return res; |
res = trace_path(&dj, fn, path, &dir); /* Trace the file path */ |
if (res == FR_OK) return FR_EXIST; /* Any file or directory is already existing */ |
if (res != FR_NO_FILE) return res; |
res = reserve_direntry(&dj, &dir); /* Reserve a directory entry */ |
if (res != FR_OK) return res; |
sect = dj.fs->winsect; |
dclust = create_chain(0); /* Allocate a cluster for new directory table */ |
if (dclust == 1) return FR_RW_ERROR; |
dsect = clust2sect(dclust); |
if (!dsect) return FR_DENIED; |
if (!move_window(dsect)) return FR_RW_ERROR; |
fw = dj.fs->win; |
memset(fw, 0, 512U); /* Clear the directory table */ |
for (n = 1; n < dj.fs->csize; n++) { |
if (disk_write(0, fw, ++dsect, 1) != RES_OK) |
return FR_RW_ERROR; |
} |
memset(&fw[DIR_Name], ' ', 8+3); /* Create "." entry */ |
fw[DIR_Name] = '.'; |
fw[DIR_Attr] = AM_DIR; |
tim = get_fattime(); |
ST_DWORD(&fw[DIR_WrtTime], tim); |
memcpy(&fw[32], &fw[0], 32); fw[33] = '.'; /* Create ".." entry */ |
pclust = dj.sclust; |
#if _FAT32 |
ST_WORD(&fw[ DIR_FstClusHI], dclust >> 16); |
if (dj.fs->fs_type == FS_FAT32 && pclust == dj.fs->dirbase) pclust = 0; |
ST_WORD(&fw[32+DIR_FstClusHI], pclust >> 16); |
#endif |
ST_WORD(&fw[ DIR_FstClusLO], dclust); |
ST_WORD(&fw[32+DIR_FstClusLO], pclust); |
dj.fs->winflag = 1; |
if (!move_window(sect)) return FR_RW_ERROR; |
memset(&dir[0], 0, 32); /* Clean-up the new entry */ |
memcpy(&dir[DIR_Name], fn, 8+3); /* Name */ |
dir[DIR_NTres] = fn[11]; |
dir[DIR_Attr] = AM_DIR; /* Attribute */ |
ST_DWORD(&dir[DIR_WrtTime], tim); /* Crated time */ |
ST_WORD(&dir[DIR_FstClusLO], dclust); /* Table start cluster */ |
#if _FAT32 |
ST_WORD(&dir[DIR_FstClusHI], dclust >> 16); |
#endif |
return sync(); |
} |
/*-----------------------------------------------------------------------*/ |
/* Change File Attribute */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_chmod ( |
const char *path, /* Pointer to the file path */ |
BYTE value, /* Attribute bits */ |
BYTE mask /* Attribute mask to change */ |
) |
{ |
FRESULT res; |
DIR dj; |
BYTE *dir; |
char fn[8+3+1]; |
res = auto_mount(&path, 1); |
if (res == FR_OK) { |
res = trace_path(&dj, fn, path, &dir); /* Trace the file path */ |
if (res == FR_OK) { /* Trace completed */ |
if (!dir) { |
res = FR_INVALID_NAME; /* Root directory */ |
} else { |
mask &= AM_RDO|AM_HID|AM_SYS|AM_ARC; /* Valid attribute mask */ |
dir[DIR_Attr] = (value & mask) | (dir[DIR_Attr] & (BYTE)~mask); /* Apply attribute change */ |
res = sync(); |
} |
} |
} |
return res; |
} |
/*-----------------------------------------------------------------------*/ |
/* Change Timestamp */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_utime ( |
const char *path, /* Pointer to the file/directory name */ |
const FILINFO *finfo /* Pointer to the timestamp to be set */ |
) |
{ |
FRESULT res; |
DIR dj; |
BYTE *dir; |
char fn[8+3+1]; |
res = auto_mount(&path, 1); |
if (res == FR_OK) { |
res = trace_path(&dj, fn, path, &dir); /* Trace the file path */ |
if (res == FR_OK) { /* Trace completed */ |
if (!dir) { |
res = FR_INVALID_NAME; /* Root directory */ |
} else { |
ST_WORD(&dir[DIR_WrtTime], finfo->ftime); |
ST_WORD(&dir[DIR_WrtDate], finfo->fdate); |
res = sync(); |
} |
} |
} |
return res; |
} |
/*-----------------------------------------------------------------------*/ |
/* Rename File/Directory */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_rename ( |
const char *path_old, /* Pointer to the old name */ |
const char *path_new /* Pointer to the new name */ |
) |
{ |
FRESULT res; |
DWORD sect_old; |
BYTE *dir_old, *dir_new, direntry[32-11]; |
DIR dj; |
char fn[8+3+1]; |
res = auto_mount(&path_old, 1); |
if (res != FR_OK) return res; |
res = trace_path(&dj, fn, path_old, &dir_old); /* Check old object */ |
if (res != FR_OK) return res; /* The old object is not found */ |
if (!dir_old) return FR_NO_FILE; |
sect_old = dj.fs->winsect; /* Save the object information */ |
memcpy(direntry, &dir_old[DIR_Attr], 32-11); |
res = trace_path(&dj, fn, path_new, &dir_new); /* Check new object */ |
if (res == FR_OK) return FR_EXIST; /* The new object name is already existing */ |
if (res != FR_NO_FILE) return res; /* Is there no old name? */ |
res = reserve_direntry(&dj, &dir_new); /* Reserve a directory entry */ |
if (res != FR_OK) return res; |
memcpy(&dir_new[DIR_Attr], direntry, 32-11); /* Create new entry */ |
memcpy(&dir_new[DIR_Name], fn, 8+3); |
dir_new[DIR_NTres] = fn[11]; |
dj.fs->winflag = 1; |
if (!move_window(sect_old)) return FR_RW_ERROR; /* Delete old entry */ |
dir_old[DIR_Name] = 0xE5; |
return sync(); |
} |
#endif /* !_FS_READONLY */ |
#endif /* _FS_MINIMIZE == 0 */ |
#endif /* _FS_MINIMIZE <= 1 */ |
#endif /* _FS_MINIMIZE <= 2 */ |
#if _USE_FORWARD |
/*-----------------------------------------------------------------------*/ |
/* Forward data to the stream directly */ |
/*-----------------------------------------------------------------------*/ |
FRESULT f_forward ( |
FIL *fp, /* Pointer to the file object */ |
UINT (*func)(const BYTE*,UINT), /* Pointer to the streaming function */ |
UINT btr, /* Number of bytes to forward */ |
UINT *br /* Pointer to number of bytes forwarded */ |
) |
{ |
FRESULT res; |
DWORD remain; |
UINT rcnt; |
CLUST clust; |
*br = 0; |
res = validate(fp->fs, fp->id); /* Check validity of the object */ |
if (res != FR_OK) return res; |
if (fp->flag & FA__ERROR) return FR_RW_ERROR; /* Check error flag */ |
if (!(fp->flag & FA_READ)) return FR_DENIED; /* Check access mode */ |
remain = fp->fsize - fp->fptr; |
if (btr > remain) btr = (UINT)remain; /* Truncate btr by remaining bytes */ |
for ( ; btr && (*func)(NULL, 0); /* Repeat until all data transferred */ |
fp->fptr += rcnt, *br += rcnt, btr -= rcnt) { |
if ((fp->fptr % 512U) == 0) { /* On the sector boundary? */ |
if (fp->csect >= fp->fs->csize) { /* On the cluster boundary? */ |
clust = (fp->fptr == 0) ? /* On the top of the file? */ |
fp->org_clust : get_cluster(fp->curr_clust); |
if (clust < 2 || clust >= fp->fs->max_clust) goto ff_error; |
fp->curr_clust = clust; /* Update current cluster */ |
fp->csect = 0; /* Reset sector address in the cluster */ |
} |
fp->csect++; /* Next sector address in the cluster */ |
} |
if (!move_window(clust2sect(fp->curr_clust) + fp->csect - 1)) /* Move sector window */ |
goto ff_error; |
rcnt = 512U - (WORD)(fp->fptr % 512U); /* Forward data from sector window */ |
if (rcnt > btr) rcnt = btr; |
rcnt = (*func)(&fp->fs->win[(WORD)fp->fptr % 512U], rcnt); |
if (rcnt == 0) goto ff_error; |
} |
return FR_OK; |
ff_error: /* Abort this function due to an unrecoverable error */ |
fp->flag |= FA__ERROR; |
return FR_RW_ERROR; |
} |
#endif /* _USE_FORWARD */ |
#if _USE_STRFUNC >= 1 |
/*-----------------------------------------------------------------------*/ |
/* Get a string from the file */ |
/*-----------------------------------------------------------------------*/ |
char* fgets ( |
char* buff, /* Pointer to the string buffer to read */ |
int len, /* Size of string buffer */ |
FIL* fil /* Pointer to the file object */ |
) |
{ |
int i = 0; |
char *p = buff; |
UINT rc; |
while (i < len - 1) { /* Read bytes until buffer gets filled */ |
f_read(fil, p, 1, &rc); |
if (rc != 1) break; /* Break when no data to read */ |
#if _USE_STRFUNC >= 2 |
if (*p == '\r') continue; /* Strip '\r' */ |
#endif |
i++; |
if (*p++ == '\n') break; /* Break when reached end of line */ |
} |
*p = 0; |
return i ? buff : 0; /* When no data read (eof or error), return with error. */ |
} |
#if !_FS_READONLY |
#include <stdarg.h> |
/*-----------------------------------------------------------------------*/ |
/* Put a character to the file */ |
/*-----------------------------------------------------------------------*/ |
int fputc ( |
int chr, /* A character to be output */ |
FIL* fil /* Ponter to the file object */ |
) |
{ |
UINT bw; |
char c; |
#if _USE_STRFUNC >= 2 |
if (chr == '\n') fputc ('\r', fil); /* LF -> CRLF conversion */ |
#endif |
if (!fil) { /* Special value may be used to switch the destination to any other device */ |
/* put_console(chr); */ |
return chr; |
} |
c = (char)chr; |
f_write(fil, &c, 1, &bw); /* Write a byte to the file */ |
return bw ? chr : EOF; /* Return the resulut */ |
} |
/*-----------------------------------------------------------------------*/ |
/* Put a string to the file */ |
/*-----------------------------------------------------------------------*/ |
int fputs ( |
const char* str, /* Pointer to the string to be output */ |
FIL* fil /* Pointer to the file object */ |
) |
{ |
int n; |
for (n = 0; *str; str++, n++) { |
if (fputc(*str, fil) == EOF) return EOF; |
} |
return n; |
} |
/*-----------------------------------------------------------------------*/ |
/* Put a formatted string to the file */ |
/*-----------------------------------------------------------------------*/ |
int fprintf ( |
FIL* fil, /* Pointer to the file object */ |
const char* str, /* Pointer to the format string */ |
... /* Optional arguments... */ |
) |
{ |
va_list arp; |
UCHAR c, f, r; |
ULONG val; |
char s[16]; |
int i, w, res, cc; |
va_start(arp, str); |
for (cc = res = 0; cc != EOF; res += cc) { |
c = *str++; |
if (c == 0) break; /* End of string */ |
if (c != '%') { /* Non escape cahracter */ |
cc = fputc(c, fil); |
if (cc != EOF) cc = 1; |
continue; |
} |
w = f = 0; |
c = *str++; |
if (c == '0') { /* Flag: '0' padding */ |
f = 1; c = *str++; |
} |
while (c >= '0' && c <= '9') { /* Precision */ |
w = w * 10 + (c - '0'); |
c = *str++; |
} |
if (c == 'l') { /* Prefix: Size is long int */ |
f |= 2; c = *str++; |
} |
if (c == 's') { /* Type is string */ |
cc = fputs(va_arg(arp, char*), fil); |
continue; |
} |
if (c == 'c') { /* Type is character */ |
cc = fputc(va_arg(arp, char), fil); |
if (cc != EOF) cc = 1; |
continue; |
} |
r = 0; |
if (c == 'd') r = 10; /* Type is signed decimal */ |
if (c == 'u') r = 10; /* Type is unsigned decimal */ |
if (c == 'X') r = 16; /* Type is unsigned hexdecimal */ |
if (r == 0) break; /* Unknown type */ |
if (f & 2) { /* Get the value */ |
val = (ULONG)va_arg(arp, long); |
} else { |
val = (c == 'd') ? (ULONG)(long)va_arg(arp, int) : (ULONG)va_arg(arp, unsigned int); |
} |
/* Put numeral string */ |
if (c == 'd') { |
if (val >= 0x80000000) { |
val = 0 - val; |
f |= 4; |
} |
} |
i = sizeof(s) - 1; s[i] = 0; |
do { |
c = (UCHAR)(val % r + '0'); |
if (c > '9') c += 7; |
s[--i] = c; |
val /= r; |
} while (i && val); |
if (i && (f & 4)) s[--i] = '-'; |
w = sizeof(s) - 1 - w; |
while (i && i > w) s[--i] = (f & 1) ? '0' : ' '; |
cc = fputs(&s[i], fil); |
} |
va_end(arp); |
return (cc == EOF) ? cc : res; |
} |
#endif /* !_FS_READONLY */ |
#endif /* _USE_STRFUNC >= 1*/ |
/programy/C/avr/SDcard/tff.h |
---|
0,0 → 1,306 |
/*--------------------------------------------------------------------------/ |
/ Tiny-FatFs - FAT file system module include file R0.06 (C)ChaN, 2008 |
/---------------------------------------------------------------------------/ |
/ FatFs module is an experimenal project to implement FAT file system to |
/ cheap microcontrollers. This is a free software and is opened for education, |
/ research and development under license policy of following trems. |
/ |
/ Copyright (C) 2008, ChaN, all right reserved. |
/ |
/ * The FatFs module is a free software and there is no warranty. |
/ * You can use, modify and/or redistribute it for personal, non-profit or |
/ commercial use without any restriction under your responsibility. |
/ * Redistributions of source code must retain the above copyright notice. |
/ |
/---------------------------------------------------------------------------*/ |
#ifndef _FATFS |
#define _MCU_ENDIAN 1 |
/* The _MCU_ENDIAN defines which access method is used to the FAT structure. |
/ 1: Enable word access. |
/ 2: Disable word access and use byte-by-byte access instead. |
/ When the architectural byte order of the MCU is big-endian and/or address |
/ miss-aligned access results incorrect behavior, the _MCU_ENDIAN must be set to 2. |
/ If it is not the case, it can also be set to 1 for good code efficiency. */ |
#define _FS_READONLY 0 |
/* Setting _FS_READONLY to 1 defines read only configuration. This removes |
/ writing functions, f_write, f_sync, f_unlink, f_mkdir, f_chmod, f_rename, |
/ f_truncate, f_getfree and internal writing codes. */ |
#define _FS_MINIMIZE 0 |
/* The _FS_MINIMIZE option defines minimization level to remove some functions. |
/ 0: Full function. |
/ 1: f_stat, f_getfree, f_unlink, f_mkdir, f_chmod, f_truncate and f_rename are removed. |
/ 2: f_opendir and f_readdir are removed in addition to level 1. |
/ 3: f_lseek is removed in addition to level 2. */ |
#define _USE_STRFUNC 0 |
/* To enable string functions, set _USE_STRFUNC to 1 or 2. */ |
#define _USE_FORWARD 0 |
/* To enable f_forward function, set _USE_FORWARD to 1. */ |
#define _FAT32 1 |
/* To enable FAT32 support in addition of FAT12/16, set _FAT32 to 1. */ |
#define _USE_FSINFO 1 |
/* To enable FSInfo support on FAT32 volume, set _USE_FSINFO to 1. */ |
#define _USE_SJIS 1 |
/* When _USE_SJIS is set to 1, Shift-JIS code transparency is enabled, otherwise |
/ only US-ASCII(7bit) code can be accepted as file/directory name. */ |
#define _USE_NTFLAG 1 |
/* When _USE_NTFLAG is set to 1, upper/lower case of the file name is preserved. |
/ Note that the files are always accessed in case insensitive. */ |
#include "integer.h" |
/* Type definition for cluster number */ |
#if _FAT32 |
typedef DWORD CLUST; |
#else |
typedef WORD CLUST; |
#undef _USE_FSINFO |
#define _USE_FSINFO 0 |
#endif |
/* File system object structure */ |
typedef struct _FATFS { |
WORD id; /* File system mount ID */ |
WORD n_rootdir; /* Number of root directory entries */ |
DWORD winsect; /* Current sector appearing in the win[] */ |
DWORD fatbase; /* FAT start sector */ |
DWORD dirbase; /* Root directory start sector */ |
DWORD database; /* Data start sector */ |
CLUST sects_fat; /* Sectors per fat */ |
CLUST max_clust; /* Maximum cluster# + 1 */ |
#if !_FS_READONLY |
CLUST last_clust; /* Last allocated cluster */ |
CLUST free_clust; /* Number of free clusters */ |
#if _USE_FSINFO |
DWORD fsi_sector; /* fsinfo sector */ |
BYTE fsi_flag; /* fsinfo dirty flag (1:must be written back) */ |
BYTE pad1; |
#endif |
#endif |
BYTE fs_type; /* FAT sub type */ |
BYTE csize; /* Number of sectors per cluster */ |
BYTE n_fats; /* Number of FAT copies */ |
BYTE winflag; /* win[] dirty flag (1:must be written back) */ |
BYTE win[512]; /* Disk access window for Directory/FAT/File */ |
} FATFS; |
/* Directory object structure */ |
typedef struct _DIR { |
WORD id; /* Owner file system mount ID */ |
WORD index; /* Current index */ |
FATFS* fs; /* Pointer to the owner file system object */ |
CLUST sclust; /* Start cluster */ |
CLUST clust; /* Current cluster */ |
DWORD sect; /* Current sector */ |
} DIR; |
/* File object structure */ |
typedef struct _FIL { |
WORD id; /* Owner file system mount ID */ |
BYTE flag; /* File status flags */ |
BYTE csect; /* Sector address in the cluster */ |
FATFS* fs; /* Pointer to owner file system */ |
DWORD fptr; /* File R/W pointer */ |
DWORD fsize; /* File size */ |
CLUST org_clust; /* File start cluster */ |
CLUST curr_clust; /* Current cluster */ |
DWORD curr_sect; /* Current sector */ |
#if !_FS_READONLY |
DWORD dir_sect; /* Sector containing the directory entry */ |
BYTE* dir_ptr; /* Ponter to the directory entry in the window */ |
#endif |
} FIL; |
/* File status structure */ |
typedef struct _FILINFO { |
DWORD fsize; /* Size */ |
WORD fdate; /* Date */ |
WORD ftime; /* Time */ |
BYTE fattrib; /* Attribute */ |
char fname[8+1+3+1]; /* Name (8.3 format) */ |
} FILINFO; |
/* File function return code (FRESULT) */ |
typedef enum { |
FR_OK = 0, /* 0 */ |
FR_NOT_READY, /* 1 */ |
FR_NO_FILE, /* 2 */ |
FR_NO_PATH, /* 3 */ |
FR_INVALID_NAME, /* 4 */ |
FR_INVALID_DRIVE, /* 5 */ |
FR_DENIED, /* 6 */ |
FR_EXIST, /* 7 */ |
FR_RW_ERROR, /* 8 */ |
FR_WRITE_PROTECTED, /* 9 */ |
FR_NOT_ENABLED, /* 10 */ |
FR_NO_FILESYSTEM, /* 11 */ |
FR_INVALID_OBJECT, /* 12 */ |
FR_MKFS_ABORTED /* 13 (not used) */ |
} FRESULT; |
/*-----------------------------------------------------*/ |
/* Tiny-FatFs module application interface */ |
FRESULT f_mount (BYTE, FATFS*); /* Mount/Unmount a logical drive */ |
FRESULT f_open (FIL*, const char*, BYTE); /* Open or create a file */ |
FRESULT f_read (FIL*, void*, UINT, UINT*); /* Read data from a file */ |
FRESULT f_write (FIL*, const void*, UINT, UINT*); /* Write data to a file */ |
FRESULT f_lseek (FIL*, DWORD); /* Move file pointer of a file object */ |
FRESULT f_close (FIL*); /* Close an open file object */ |
FRESULT f_opendir (DIR*, const char*); /* Open an existing directory */ |
FRESULT f_readdir (DIR*, FILINFO*); /* Read a directory item */ |
FRESULT f_stat (const char*, FILINFO*); /* Get file status */ |
FRESULT f_getfree (const char*, DWORD*, FATFS**); /* Get number of free clusters on the drive */ |
FRESULT f_truncate (FIL*); /* Truncate file */ |
FRESULT f_sync (FIL*); /* Flush cached data of a writing file */ |
FRESULT f_unlink (const char*); /* Delete an existing file or directory */ |
FRESULT f_mkdir (const char*); /* Create a new directory */ |
FRESULT f_chmod (const char*, BYTE, BYTE); /* Change file/dir attriburte */ |
FRESULT f_utime (const char*, const FILINFO*); /* Change file/dir timestamp */ |
FRESULT f_rename (const char*, const char*); /* Rename/Move a file or directory */ |
FRESULT f_forward (FIL*, UINT(*)(const BYTE*,UINT), UINT, UINT*); /* Forward data to the stream */ |
#if _USE_STRFUNC |
#define feof(fp) ((fp)->fptr == (fp)->fsize) |
#define EOF -1 |
int fputc (int, FIL*); /* Put a character to the file */ |
int fputs (const char*, FIL*); /* Put a string to the file */ |
int fprintf (FIL*, const char*, ...); /* Put a formatted string to the file */ |
char* fgets (char*, int, FIL*); /* Get a string from the file */ |
#endif |
/* User defined function to give a current time to fatfs module */ |
DWORD get_fattime (void); /* 31-25: Year(0-127 +1980), 24-21: Month(1-12), 20-16: Day(1-31) */ |
/* 15-11: Hour(0-23), 10-5: Minute(0-59), 4-0: Second(0-29 *2) */ |
/* File access control and file status flags (FIL.flag) */ |
#define FA_READ 0x01 |
#define FA_OPEN_EXISTING 0x00 |
#if !_FS_READONLY |
#define FA_WRITE 0x02 |
#define FA_CREATE_NEW 0x04 |
#define FA_CREATE_ALWAYS 0x08 |
#define FA_OPEN_ALWAYS 0x10 |
#define FA__WRITTEN 0x20 |
#endif |
#define FA__ERROR 0x80 |
/* FAT sub type (FATFS.fs_type) */ |
#define FS_FAT12 1 |
#define FS_FAT16 2 |
#define FS_FAT32 3 |
/* File attribute bits for directory entry */ |
#define AM_RDO 0x01 /* Read only */ |
#define AM_HID 0x02 /* Hidden */ |
#define AM_SYS 0x04 /* System */ |
#define AM_VOL 0x08 /* Volume label */ |
#define AM_LFN 0x0F /* LFN entry */ |
#define AM_DIR 0x10 /* Directory */ |
#define AM_ARC 0x20 /* Archive */ |
/* Offset of FAT structure members */ |
#define BS_jmpBoot 0 |
#define BS_OEMName 3 |
#define BPB_BytsPerSec 11 |
#define BPB_SecPerClus 13 |
#define BPB_RsvdSecCnt 14 |
#define BPB_NumFATs 16 |
#define BPB_RootEntCnt 17 |
#define BPB_TotSec16 19 |
#define BPB_Media 21 |
#define BPB_FATSz16 22 |
#define BPB_SecPerTrk 24 |
#define BPB_NumHeads 26 |
#define BPB_HiddSec 28 |
#define BPB_TotSec32 32 |
#define BS_55AA 510 |
#define BS_DrvNum 36 |
#define BS_BootSig 38 |
#define BS_VolID 39 |
#define BS_VolLab 43 |
#define BS_FilSysType 54 |
#define BPB_FATSz32 36 |
#define BPB_ExtFlags 40 |
#define BPB_FSVer 42 |
#define BPB_RootClus 44 |
#define BPB_FSInfo 48 |
#define BPB_BkBootSec 50 |
#define BS_DrvNum32 64 |
#define BS_BootSig32 66 |
#define BS_VolID32 67 |
#define BS_VolLab32 71 |
#define BS_FilSysType32 82 |
#define FSI_LeadSig 0 |
#define FSI_StrucSig 484 |
#define FSI_Free_Count 488 |
#define FSI_Nxt_Free 492 |
#define MBR_Table 446 |
#define DIR_Name 0 |
#define DIR_Attr 11 |
#define DIR_NTres 12 |
#define DIR_CrtTime 14 |
#define DIR_CrtDate 16 |
#define DIR_FstClusHI 20 |
#define DIR_WrtTime 22 |
#define DIR_WrtDate 24 |
#define DIR_FstClusLO 26 |
#define DIR_FileSize 28 |
/* Multi-byte word access macros */ |
#if _MCU_ENDIAN == 1 /* Use word access */ |
#define LD_WORD(ptr) (WORD)(*(WORD*)(BYTE*)(ptr)) |
#define LD_DWORD(ptr) (DWORD)(*(DWORD*)(BYTE*)(ptr)) |
#define ST_WORD(ptr,val) *(WORD*)(BYTE*)(ptr)=(WORD)(val) |
#define ST_DWORD(ptr,val) *(DWORD*)(BYTE*)(ptr)=(DWORD)(val) |
#elif _MCU_ENDIAN == 2 /* Use byte-by-byte access */ |
#define LD_WORD(ptr) (WORD)(((WORD)*(volatile BYTE*)((ptr)+1)<<8)|(WORD)*(volatile BYTE*)(ptr)) |
#define LD_DWORD(ptr) (DWORD)(((DWORD)*(volatile BYTE*)((ptr)+3)<<24)|((DWORD)*(volatile BYTE*)((ptr)+2)<<16)|((WORD)*(volatile BYTE*)((ptr)+1)<<8)|*(volatile BYTE*)(ptr)) |
#define ST_WORD(ptr,val) *(volatile BYTE*)(ptr)=(BYTE)(val); *(volatile BYTE*)((ptr)+1)=(BYTE)((WORD)(val)>>8) |
#define ST_DWORD(ptr,val) *(volatile BYTE*)(ptr)=(BYTE)(val); *(volatile BYTE*)((ptr)+1)=(BYTE)((WORD)(val)>>8); *(volatile BYTE*)((ptr)+2)=(BYTE)((DWORD)(val)>>16); *(volatile BYTE*)((ptr)+3)=(BYTE)((DWORD)(val)>>24) |
#else |
#error Do not forget to set _MCU_ENDIAN properly! |
#endif |
#define _FATFS |
#endif /* _FATFS */ |
/programy/C/avr/SDcard/tt.ini |
---|
0,0 → 1,0 |
bps=115200 |
/programy/C/avr/SDcard/uart.c |
---|
0,0 → 1,128 |
/*------------------------------------------------*/ |
/* UART functions */ |
#include <avr/io.h> |
#include <avr/interrupt.h> |
#include "uart.h" |
#define SYSCLK 9216000 |
#define BAUD 115200 |
typedef struct _fifo { |
uint8_t idx_w; |
uint8_t idx_r; |
uint8_t count; |
uint8_t buff[64]; |
} FIFO; |
static volatile |
FIFO txfifo, rxfifo; |
/* Initialize UART */ |
void uart_init() |
{ |
rxfifo.idx_r = 0; |
rxfifo.idx_w = 0; |
rxfifo.count = 0; |
txfifo.idx_r = 0; |
txfifo.idx_w = 0; |
txfifo.count = 0; |
UBRR0L = SYSCLK/BAUD/16-1; |
UCSR0B = _BV(RXEN0)|_BV(RXCIE0)|_BV(TXEN0); |
} |
/* Get a received character */ |
uint8_t uart_test () |
{ |
return rxfifo.count; |
} |
uint8_t uart_get () |
{ |
uint8_t d, i; |
i = rxfifo.idx_r; |
while(rxfifo.count == 0); |
d = rxfifo.buff[i++]; |
cli(); |
rxfifo.count--; |
sei(); |
if(i >= sizeof(rxfifo.buff)) |
i = 0; |
rxfifo.idx_r = i; |
return d; |
} |
/* Put a character to transmit */ |
void uart_put (uint8_t d) |
{ |
uint8_t i; |
i = txfifo.idx_w; |
while(txfifo.count >= sizeof(txfifo.buff)); |
txfifo.buff[i++] = d; |
cli(); |
txfifo.count++; |
UCSR0B = _BV(RXEN0)|_BV(RXCIE0)|_BV(TXEN0)|_BV(UDRIE0); |
sei(); |
if(i >= sizeof(txfifo.buff)) |
i = 0; |
txfifo.idx_w = i; |
} |
/* UART RXC interrupt */ |
SIGNAL(SIG_UART0_RECV) |
{ |
uint8_t d, n, i; |
d = UDR0; |
n = rxfifo.count; |
if(n < sizeof(rxfifo.buff)) { |
rxfifo.count = ++n; |
i = rxfifo.idx_w; |
rxfifo.buff[i++] = d; |
if(i >= sizeof(rxfifo.buff)) |
i = 0; |
rxfifo.idx_w = i; |
} |
} |
/* UART UDRE interrupt */ |
SIGNAL(SIG_UART0_DATA) |
{ |
uint8_t n, i; |
n = txfifo.count; |
if(n) { |
txfifo.count = --n; |
i = txfifo.idx_r; |
UDR0 = txfifo.buff[i++]; |
if(i >= sizeof(txfifo.buff)) |
i = 0; |
txfifo.idx_r = i; |
} |
if(n == 0) |
UCSR0B = _BV(RXEN0)|_BV(RXCIE0)|_BV(TXEN0); |
} |
/programy/C/avr/SDcard/uart.h |
---|
0,0 → 1,6 |
#include "uart.c" |
void uart_init(void); /* Initialize UART and Flush FIFOs */ |
uint8_t uart_get (void); /* Get a byte from UART Rx FIFO */ |
uint8_t uart_test(void); /* Check number of data in UART Rx FIFO */ |
void uart_put (uint8_t); /* Put a byte into UART Tx FIFO */ |
/programy/C/avr/SDcard/xitoa.S |
---|
0,0 → 1,415 |
;---------------------------------------------------------------------------; |
; Extended itoa, puts, printf and atoi (C)ChaN, 2006 |
; |
; Module size: 277/261 words (max) |
; |
#define USE_XPUTS |
#define USE_XITOA |
#define USE_XPRINTF |
#define USE_XATOI |
.nolist |
#include <avr/io.h> // Include device specific definitions. |
.list |
#ifdef SPM_PAGESIZE // Recent devices have "lpm Rd,Z+" and "movw". |
.macro _LPMI reg |
lpm \reg, Z+ |
.endm |
.macro _MOVW dh,dl, sh,sl |
movw \dl, \sl |
.endm |
#else // Earlier devices do not have "lpm Rd,Z+" nor "movw". |
.macro _LPMI reg |
lpm |
mov \reg, r0 |
adiw ZL, 1 |
.endm |
.macro _MOVW dh,dl, sh,sl |
mov \dl, \sl |
mov \dh, \sh |
.endm |
#endif |
;--------------------------------------------------------------------------- |
; Stub function to forward to user output function |
; |
;Prototype: void xputc (char chr // a character to be output |
; ); |
;Size: 15/15 words |
.section .bss |
.global xfunc_out ; xfunc_out must be initialized before using this module. |
xfunc_out: .ds.w 1 |
.section .text |
.global xputc |
.func xputc |
xputc: |
cpi r24, 10 ;LF --> CRLF |
brne 1f ; |
ldi r24, 13 ; |
rcall 1f ; |
ldi r24, 10 ;/ |
1: push ZH |
push ZL |
lds ZL, xfunc_out+0 ;Pointer to the registered output function. |
lds ZH, xfunc_out+1 ;/ |
icall |
pop ZL |
pop ZH |
ret |
.endfunc |
;--------------------------------------------------------------------------- |
; Direct ROM string output |
; |
;Prototype: void xputs (const prog_char *str // rom string to be output |
; ); |
;Size: 10/7 words |
#ifdef USE_XPUTS |
.global xputs |
.func xputs |
xputs: |
_MOVW ZH,ZL, r25,r24 ; Z = pointer to rom string |
1: _LPMI r24 |
cpi r24, 0 |
breq 2f |
rcall xputc |
rjmp 1b |
2: ret |
.endfunc |
#endif |
;--------------------------------------------------------------------------- |
; Extended direct numeral string output (32bit version) |
; |
;Prototype: void xitoa (long value, // value to be output |
; char radix, // radix |
; char width); // minimum width |
;Size: 59/59 words |
; |
#ifdef USE_XITOA |
.global xitoa |
.func xitoa |
xitoa: |
;r25:r22 = value, r20 = base, r18 = digits |
clr r31 ;r31 = stack level |
ldi r30, ' ' ;r30 = sign |
ldi r19, ' ' ;r19 = filler |
sbrs r20, 7 ;When base indicates signd format and the value |
rjmp 0f ;is minus, add a '-'. |
neg r20 ; |
sbrs r25, 7 ; |
rjmp 0f ; |
ldi r30, '-' ; |
com r22 ; |
com r23 ; |
com r24 ; |
com r25 ; |
adc r22, r1 ; |
adc r23, r1 ; |
adc r24, r1 ; |
adc r25, r1 ;/ |
0: sbrs r18, 7 ;When digits indicates zero filled, |
rjmp 1f ;filler is '0'. |
neg r18 ; |
ldi r19, '0' ;/ |
;----- string conversion loop |
1: ldi r21, 32 ;r26 = r25:r22 % r20 |
clr r26 ;r25:r22 /= r20 |
2: lsl r22 ; |
rol r23 ; |
rol r24 ; |
rol r25 ; |
rol r26 ; |
cp r26, r20 ; |
brcs 3f ; |
sub r26, r20 ; |
inc r22 ; |
3: dec r21 ; |
brne 2b ;/ |
cpi r26, 10 ;r26 is a numeral digit '0'-'F' |
brcs 4f ; |
subi r26, -7 ; |
4: subi r26, -'0' ;/ |
push r26 ;Stack it |
inc r31 ;/ |
cp r22, r1 ;Repeat until r25:r22 gets zero |
cpc r23, r1 ; |
cpc r24, r1 ; |
cpc r25, r1 ; |
brne 1b ;/ |
cpi r30, '-' ;Minus sign if needed |
brne 5f ; |
push r30 ; |
inc r31 ;/ |
5: cp r31, r18 ;Filler |
brcc 6f ; |
push r19 ; |
inc r31 ; |
rjmp 5b ;/ |
6: pop r24 ;Flush stacked digits and exit |
rcall xputc ; |
dec r31 ; |
brne 6b ;/ |
ret |
.endfunc |
#endif |
;---------------------------------------------------------------------------; |
; Formatted string output (16/32bit version) |
; |
;Prototype: |
; void xprintf (const prog_char *format, ...); |
;Size: 104/94 words |
; |
#ifdef USE_XPRINTF |
.global xprintf |
.func xprintf |
xprintf: |
push YH |
push YL |
in YL, _SFR_IO_ADDR(SPL) |
#ifdef SPH |
in YH, _SFR_IO_ADDR(SPH) |
#else |
clr YH |
#endif |
#if FLASHEND > 0x1FFFF |
adiw YL, 6 ;Y = pointer to arguments |
#else |
adiw YL, 5 ;Y = pointer to arguments |
#endif |
ld ZL, Y+ ;Z = pointer to format string |
ld ZH, Y+ ;/ |
0: _LPMI r24 ;Get a format char |
cpi r24, 0 ;End of format string? |
breq 90f ;/ |
cpi r24, '%' ;Is format? |
breq 20f ;/ |
1: rcall xputc ;Put a normal character |
rjmp 0b ;/ |
90: pop YL |
pop YH |
ret |
20: ldi r18, 0 ;r18: digits |
clt ;T: filler |
_LPMI r21 ;Get flags |
cpi r21, '%' ;Is a %? |
breq 1b ;/ |
cpi r21, '0' ;Zero filled? |
brne 23f ; |
set ;/ |
22: _LPMI r21 ;Get width |
23: cpi r21, '9'+1 ; |
brcc 24f ; |
subi r21, '0' ; |
brcs 90b ; |
lsl r18 ; |
mov r0, r18 ; |
lsl r18 ; |
lsl r18 ; |
add r18, r0 ; |
add r18, r21 ; |
rjmp 22b ;/ |
24: brtc 25f ;get value (low word) |
neg r18 ; |
25: ld r24, Y+ ; |
ld r25, Y+ ;/ |
cpi r21, 'c' ;Is type character? |
breq 1b ;/ |
cpi r21, 's' ;Is type RAM string? |
breq 50f ;/ |
cpi r21, 'S' ;Is type ROM string? |
breq 60f ;/ |
_MOVW r23,r22,r25,r24 ;r25:r22 = value |
clr r24 ; |
clr r25 ; |
clt ;/ |
cpi r21, 'l' ;Is long int? |
brne 26f ; |
ld r24, Y+ ;get value (high word) |
ld r25, Y+ ; |
set ; |
_LPMI r21 ;/ |
26: cpi r21, 'd' ;Is type signed decimal? |
brne 27f ;/ |
ldi r20, -10 ; |
brts 40f ; |
sbrs r23, 7 ; |
rjmp 40f ; |
ldi r24, -1 ; |
ldi r25, -1 ; |
rjmp 40f ;/ |
27: cpi r21, 'u' ;Is type unsigned decimal? |
ldi r20, 10 ; |
breq 40f ;/ |
cpi r21, 'X' ;Is type hexdecimal? |
ldi r20, 16 ; |
breq 40f ;/ |
cpi r21, 'b' ;Is type binary? |
ldi r20, 2 ; |
breq 40f ;/ |
rjmp 90b ;abort |
40: push ZH ;Output the value |
push ZL ; |
rcall xitoa ; |
42: pop ZL ; |
pop ZH ; |
rjmp 0b ;/ |
50: push ZH ;Put a string on the RAM |
push ZL |
_MOVW ZH,ZL, r25,r24 |
51: ld r24, Z+ |
cpi r24, 0 |
breq 42b |
rcall xputc |
rjmp 51b |
60: push ZH ;Put a string on the ROM |
push ZL |
rcall xputs |
rjmp 42b |
.endfunc |
#endif |
;--------------------------------------------------------------------------- |
; Extended numeral string input |
; |
;Prototype: |
; char xatoi ( /* 1: Successful, 0: Failed */ |
; const char **str, /* pointer to pointer to source string */ |
; long *res /* result */ |
; ); |
;Size: 94/91 words |
; |
#ifdef USE_XATOI |
.global xatoi |
.func xatoi |
xatoi: |
_MOVW r1, r0, r23, r22 |
_MOVW XH, XL, r25, r24 |
ld ZL, X+ |
ld ZH, X+ |
clr r18 ;r21:r18 = 0; |
clr r19 ; |
clr r20 ; |
clr r21 ;/ |
clt ;T = 0; |
ldi r25, 10 ;r25 = 10; |
rjmp 41f ;/ |
40: adiw ZL, 1 ;Z++; |
41: ld r22, Z ;r22 = *Z; |
cpi r22, ' ' ;if(r22 == ' ') continue |
breq 40b ;/ |
brcs 70f ;if(r22 < ' ') error; |
cpi r22, '-' ;if(r22 == '-') { |
brne 42f ; T = 1; |
set ; continue; |
rjmp 40b ;} |
42: cpi r22, '9'+1 ;if(r22 > '9') error; |
brcc 70f ;/ |
cpi r22, '0' ;if(r22 < '0') error; |
brcs 70f ;/ |
brne 51f ;if(r22 > '0') cv_start; |
ldi r25, 8 ;r25 = 8; |
adiw ZL, 1 ;r22 = *(++Z); |
ld r22, Z ;/ |
cpi r22, ' '+1 ;if(r22 <= ' ') exit; |
brcs 80f ;/ |
cpi r22, 'b' ;if(r22 == 'b') { |
brne 43f ; r25 = 2; |
ldi r25, 2 ; cv_start; |
rjmp 50f ;} |
43: cpi r22, 'x' ;if(r22 != 'x') error; |
brne 51f ;/ |
ldi r25, 16 ;r25 = 16; |
50: adiw ZL, 1 ;Z++; |
ld r22, Z ;r22 = *Z; |
51: cpi r22, ' '+1 ;if(r22 <= ' ') break; |
brcs 80f ;/ |
cpi r22, 'a' ;if(r22 >= 'a') r22 =- 0x20; |
brcs 52f ; |
subi r22, 0x20 ;/ |
52: subi r22, '0' ;if((r22 -= '0') < 0) error; |
brcs 70f ;/ |
cpi r22, 10 ;if(r22 >= 10) { |
brcs 53f ; r22 -= 7; |
subi r22, 7 ; if(r22 < 10) |
cpi r22, 10 ; |
brcs 70f ;} |
53: cp r22, r25 ;if(r22 >= r25) error; |
brcc 70f ;/ |
60: ldi r24, 33 ;r21:r18 *= r25; |
sub r23, r23 ; |
61: brcc 62f ; |
add r23, r25 ; |
62: lsr r23 ; |
ror r21 ; |
ror r20 ; |
ror r19 ; |
ror r18 ; |
dec r24 ; |
brne 61b ;/ |
add r18, r22 ;r21:r18 += r22; |
adc r19, r24 ; |
adc r20, r24 ; |
adc r21, r24 ;/ |
rjmp 50b ;repeat |
70: ldi r24, 0 |
rjmp 81f |
80: ldi r24, 1 |
81: brtc 82f |
clr r22 |
com r18 |
com r19 |
com r20 |
com r21 |
adc r18, r22 |
adc r19, r22 |
adc r20, r22 |
adc r21, r22 |
82: st -X, ZH |
st -X, ZL |
_MOVW XH, XL, r1, r0 |
st X+, r18 |
st X+, r19 |
st X+, r20 |
st X+, r21 |
clr r1 |
ret |
.endfunc |
#endif |
/programy/C/avr/SDcard/xitoa.h |
---|
0,0 → 1,97 |
/*--------------------------------------------------------------------------- |
Extended itoa, puts and printf (C)ChaN, 2006 |
-----------------------------------------------------------------------------*/ |
#ifndef XITOA |
#define XITOA |
#include <avr/pgmspace.h> |
#include "xitoa.S" |
extern void (*xfunc_out)(char); |
/* This is a pointer to user defined output function. It must be initialized |
before using this modle. |
*/ |
void xputc(char chr); |
/* This is a stub function to forward outputs to user defined output function. |
All outputs from this module are output via this function. |
*/ |
/*-----------------------------------------------------------------------------*/ |
void xputs(const prog_char *string); |
/* The string placed in the ROM is forwarded to xputc() directly. |
*/ |
/*-----------------------------------------------------------------------------*/ |
void xitoa(long value, char radix, char width); |
/* Extended itoa(). |
value radix width output |
100 10 6 " 100" |
100 10 -6 "000100" |
100 10 0 "100" |
4294967295 10 0 "4294967295" |
4294967295 -10 0 "-1" |
655360 16 -8 "000A0000" |
1024 16 0 "400" |
0x55 2 -8 "01010101" |
*/ |
/*-----------------------------------------------------------------------------*/ |
void xprintf(const prog_char *format, ...); |
/* Format string is placed in the ROM. The format flags is similar to printf(). |
%[flag][width][size]type |
flag |
A '0' means filled with '0' when output is shorter than width. |
' ' is used in default. This is effective only numeral type. |
width |
Minimum width in decimal number. This is effective only numeral type. |
Default width is zero. |
size |
A 'l' means the argument is long(32bit). Default is short(16bit). |
This is effective only numeral type. |
type |
'c' : Character, argument is the value |
's' : String placed on the RAM, argument is the pointer |
'S' : String placed on the ROM, argument is the pointer |
'd' : Signed decimal, argument is the value |
'u' : Unsigned decimal, argument is the value |
'X' : Hex decimal, argument is the value |
'b' : Binary, argument is the value |
'%' : '%' |
*/ |
/*-----------------------------------------------------------------------------*/ |
char xatoi(char **str, long *ret); |
/* Get value of the numeral string. |
str |
Pointer to pointer to source string |
"0b11001010" binary |
"0377" octal |
"0xff800" hexdecimal |
"1250000" decimal |
"-25000" decimal |
ret |
Pointer to return value |
*/ |
#endif /* XITOA */ |