Compact Flash Library

The Compact Flash Library provides routines for accessing data on Compact Flash card (abbr. CF further in text). CF cards are widely used memory elements, commonly used with digital cameras. Great capacity and excellent access time of only a few microseconds make them very attractive for microcontroller applications.

In CF card, data is divided into sectors. One sector usually comprises 512 bytes. Routines for file handling, the Cf_Fat routines, are not performed directly but successively through 512B buffer.

  Important :

Library Dependency Tree

Compact Flash Library Dependency Tree

External dependencies of Compact Flash Library

The following variables must be defined in all projects using Compact Flash Library: Description : Example :
extern sfr atomic unsigned long CF_Data_Port; Compact Flash Data Port. unsigned long CF_Data_Port at PORTF;
extern sfr atomic sbit CF_RDY; Ready signal line. sbit CF_RDY at RD7_bit;
extern sfr atomic sbit CF_WE; Write Enable signal line. sbit CF_WE at RD6_bit;
extern sfr atomic sbit CF_OE; Output Enable signal line. sbit CF_OE at RD5_bit;
extern sfr atomic sbit CF_CD1; Chip Detect signal line. sbit CF_CD1 at RD4_bit;
extern sfr atomic sbit CF_CE1; Chip Enable signal line. sbit CF_CE1 at RD3_bit;
extern sfr atomic sbit CF_A2; Address pin 2. sbit CF_A2 at RD2_bit;
extern sfr atomic sbit CF_A1; Address pin 1. sbit CF_A1 at RD1_bit;
extern sfr atomic sbit CF_A0; Address pin 0. sbit CF_A0 at RD0_bit;
extern sfr atomic sbit CF_RDY_direction; Direction of the Ready pin. sbit CF_RDY_direction at TRISD7_bit;
extern sfr atomic sbit CF_WE_direction; Direction of the Write Enable pin. sbit CF_WE_direction at TRISDB6_bit;
extern sfr atomic sbit CF_OE_direction; Direction of the Output Enable pin. sbit CF_OE_direction at TRISD5_bit;
extern sfr atomic sbit CF_CD1_direction; Direction of the Chip Detect pin. sbit CF_CD1_direction at TRISD4_bit;
extern sfr atomic sbit CF_CE1_direction; Direction of the Chip Enable pin. sbit CF_CE1_direction at TRISD3_bit;
extern sfr atomic sbit CF_A2_direction; Direction of the Address 2 pin. sbit CF_A2_direction at TRISD2_bit;
extern sfr atomic sbit CF_A1_direction; Direction of the Address 1 pin. sbit CF_A1_direction at TRISD1_bit;
extern sfr atomic sbit CF_A0_direction; Direction of the Address 0 pin. sbit CF_A0_direction at TRISD0_bit;

Library Routines

Routines for file handling:

The following routine is for the internal use by compiler only:

Cf_Init

Prototype

void Cf_Init();

Description

Initializes ports appropriately for communication with CF card.

Parameters

None.

Returns

Nothing.

Requires

Global variables :

  • CF_Data_Port : Compact Flash data port
  • CF_RDY : Ready signal line
  • CF_WE : Write enable signal line
  • CF_OE : Output enable signal line
  • CF_CD1 : Chip detect signal line
  • CF_CE1 : Enable signal line
  • CF_A2 : Address pin 2
  • CF_A1 : Address pin 1
  • CF_A0 : Address pin 0

  • CF_RDY_direction : Direction of the Ready pin
  • CF_WE_direction : Direction of the Write enable pin
  • CF_OE_direction : Direction of the Output enable pin
  • CF_CD1_direction : Direction of the Chip detect pin
  • CF_CE1_direction : Direction of the Chip enable pin
  • CF_A2_direction : Direction of the Address 2 pin
  • CF_A1_direction : Direction of the Address 1 pin
  • CF_A0_direction : Direction of the Address 0 pin
must be defined before using this function.

Example
// set compact flash pinout 
char Cf_Data_Port at PORTF;

sbit CF_RDY at RD7_bit;
sbit CF_WE  at RD6_bit;
sbit CF_OE  at RD5_bit;
sbit CF_CD1 at RD4_bit;
sbit CF_CE1 at RD3_bit;
sbit CF_A2  at RD2_bit;
sbit CF_A1  at RD1_bit;
sbit CF_A0  at RD0_bit;

sbit CF_RDY_direction at TRISD7_bit;
sbit CF_WE_direction  at TRISD6_bit;
sbit CF_OE_direction  at TRISD5_bit;
sbit CF_CD1_direction at TRISD4_bit;
sbit CF_CE1_direction at TRISD3_bit;
sbit CF_A2_direction  at TRISD2_bit;
sbit CF_A1_direction  at TRISD1_bit;
sbit CF_A0_direction  at TRISD0_bit;
// end of compact flash pinout
...
Cf_Init();      // initialize CF 
Notes

None.

Cf_Detect

Prototype

unsigned int Cf_Detect();

Description

Checks for presence of CF card by reading the chip detect pin.

Parameters

None.

Returns

  • 1 - if CF card was detected
  • 0 - otherwise

Requires

The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.

Example
// Wait until CF card is inserted:
do
  asm nop;
while (!Cf_Detect());
Notes

PIC32 family MCU and CF card voltage levels are different. The user must ensure that MCU's pin connected to CD line can read CF card Logical One correctly.

Cf_Enable

Prototype

void Cf_Enable();

Description

Enables the device. Routine needs to be called only if you have disabled the device by means of the Cf_Disable routine. These two routines in conjunction allow you to free/occupy data line when working with multiple devices.

Parameters

None.

Returns

Nothing.

Requires

The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.

Example
// enable compact flash
Cf_Enable();
Notes

None.

Cf_Disable

Prototype

void Cf_Disable();

Description

Routine disables the device and frees the data lines for other devices. To enable the device again, call Cf_Enable. These two routines in conjunction allow you to free/occupy data line when working with multiple devices.

Parameters

None.

Returns

Nothing.

Requires

The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.

Example
// disable compact flash
Cf_Disable();
Notes

None.

Cf_Read_Init

Prototype

void Cf_Read_Init(unsigned long address, unsigned short sector_count);

Description

Initializes CF card for reading.

Parameters
  • address: the first sector to be prepared for reading operation.
  • sector_count: number of sectors to be prepared for reading operation.
Returns

Nothing.

Requires

The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.

Example
// initialize compact flash for reading from sector 590
Cf_Read_Init(590, 1);
Notes

None.

Cf_Read_Byte

Prototype

unsigned char Cf_Read_Byte();

Description

Reads one byte from Compact Flash sector buffer location currently pointed to by internal read pointers. These pointers will be autoicremented upon reading.

Parameters

None.

Returns

Returns a byte read from Compact Flash sector buffer.

Requires

The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.

CF card must be initialized for reading operation. See Cf_Read_Init.

Example
// Read a byte from compact flash:
unsigned char data_;
...
data_ = Cf_Read_Byte();
Notes Higher byte of the unsigned return value is cleared.

Cf_Write_Init

Prototype

void Cf_Write_Init(unsigned long address, unsigned short sectcnt);

Description

Initializes CF card for writing.

Parameters
  • address: the first sector to be prepared for writing operation.
  • sectcnt: number of sectors to be prepared for writing operation.
Returns

Nothing.

Requires

The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.

Example
// initialize compact flash for writing to sector 590
Cf_Write_Init(590, 1);
Notes

None.

Cf_Write_Byte

Prototype

void Cf_Write_Byte(unsigned short data_);

Description

Writes a byte to Compact Flash sector buffer location currently pointed to by writing pointers. These pointers will be autoicremented upon reading. When sector buffer is full, its contents will be transfered to appropriate flash memory sector.

Parameters
  • data_: byte to be written.
Returns

Nothing.

Requires

The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.

CF card must be initialized for writing operation. See Cf_Write_Init.

Example
char data_ = 0xAA;
...
Cf_Write_Byte(data_);
Notes

None.

Cf_Read_Sector

Prototype

void Cf_Read_Sector(unsigned long sector_number, unsigned short *buffer);

Description

Reads one sector (512 bytes). Read data is stored into buffer provided by the buffer parameter.

Parameters
  • sector_number: sector to be read.
  • buffer: data buffer of at least 512 bytes in length.
Returns

Nothing.

Requires

The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.

Example
// read sector 22
unsigned short data[512];
...
Cf_Read_Sector(22, data);
Notes

None.

Cf_Write_Sector

Prototype

void Cf_Write_Sector(unsigned long sector_number, unsigned short *buffer);

Description

Writes 512 bytes of data provided by the buffer parameter to one CF sector.

Parameters
  • sector_number: sector to be written to.
  • buffer: data buffer of 512 bytes in length.
Returns

Nothing.

Requires

The corresponding MCU ports must be appropriately initialized for CF card. See Cf_Init.

Example
// write to sector 22
unsigned short data[512];
...
Cf_Write_Sector(22, data);
Notes

None.

Cf_Fat_Init

Prototype

unsigned int Cf_Fat_Init();

Description

Initializes CF card, reads CF FAT16 boot sector and extracts necessary data needed by the library.

Parameters

None.

Returns

  • 0 - if CF card was detected and successfully initialized
  • 1 - if FAT16 boot sector was not found
  • 255 - if card was not detected

Requires

Nothing.

Example
// Init the FAT library
if (!Cf_Fat_Init()) {    // Init the FAT library
...
}
Notes

None.

Cf_Fat_QuickFormat

Prototype

unsigned int Cf_Fat_QuickFormat(char *cf_fat_label);

Description

Formats to FAT16 and initializes CF card.

Parameters
  • cf_fat_label: volume label (11 characters in length). If less than 11 characters are provided, the label will be padded with spaces. If null string is passed, the volume will not be labeled.
Returns

  • 0 - if CF card was detected, successfully formated and initialized
  • 1 - if FAT16 format was unsuccessful
  • 255 - if card was not detected

Requires

Nothing.

Example
//  format and initialize the FAT library - 
if (!Cf_Fat_QuickFormat(&cf_fat_label)) {
...
}
Notes
  • This routine can be used instead or in conjunction with Cf_Fat_Init routine.
  • If CF card already contains a valid boot sector, it will remain unchanged (except volume label field) and only FAT and ROOT tables will be erased. Also, the new volume label will be set.

Cf_Fat_Assign

Prototype

unsigned int Cf_Fat_Assign(char *filename, char file_cre_attr);

Description

Assigns file for file operations (read, write, delete...). All subsequent file operations will be applied over the assigned file.

Parameters
  • filename: name of the file that should be assigned for file operations. The file name should be in DOS 8.3 (file_name.extension) format. The file name and extension will be automatically padded with spaces by the library if they have less than length required (i.e. "mikro.tx" -> "mikro .tx "), so the user does not have to take care of that. The file name and extension are case insensitive. The library will convert them to proper case automatically, so the user does not have to take care of that.

    Also, in order to keep backward compatibility with the first version of this library, file names can be entered as UPPERCASE string of 11 bytes in length with no dot character between the file name and extension (i.e. "MIKROELETXT" -> MIKROELE.TXT). In this case the last 3 characters of the string are considered to be file extension.

  • file_cre_attr: file creation and attributes flags. Each bit corresponds to the appropriate file attribute:
  • Bit Mask Description
    0 0x01 Read Only
    1 0x02 Hidden
    2 0x04 System
    3 0x08 Volume Label
    4 0x10 Subdirectory
    5 0x20 Archive
    6 0x40 Device (internal use only, never found on disk)
    7 0x80 File creation flag. If the file does not exist and this flag is set, a new file with specified name will be created.
Returns

  • 0 if file does not exist and no new file is created.
  • 1 if file already exists or file does not exist but a new file is created.

Requires

CF card and CF library must be initialized for file operations. See Cf_Fat_Init.

Example
// create file with archive attributes if it does not already exist
Cf_Fat_Assign("MIKRO007.TXT",0xA0);
Notes Long File Names (LFN) are not supported.

Cf_Fat_Reset

Prototype

void Cf_Fat_Reset(unsigned long *size);

Description

Opens currently assigned file for reading.

Parameters
  • size: buffer to store file size to. After file has been open for reading its size is returned through this parameter.
Returns

Nothing.

Requires

CF card and CF library must be initialized for file operations. See Cf_Fat_Init.

File must be previously assigned. See Cf_Fat_Assign.

Example
unsigned long size;
...
Cf_Fat_Reset(size);
Notes

None.

Cf_Fat_Read

Prototype

void Cf_Fat_Read(unsigned short *bdata);

Description

Reads a byte from currently assigned file opened for reading. Upon function execution file pointers will be set to the next character in the file.

Parameters
  • bdata: buffer to store read byte to. Upon this function execution read byte is returned through this parameter.
Returns

Nothing.

Requires

CF card and CF library must be initialized for file operations. See Cf_Fat_Init.

File must be previously assigned. See Cf_Fat_Assign.

File must be open for reading. See Cf_Fat_Reset.

Example
char character;
...
Cf_Fat_Read(&character);
Notes

None.

Cf_Fat_Rewrite

Prototype

void Cf_Fat_Rewrite();

Description

Opens currently assigned file for writing. If the file is not empty its content will be erased.

Parameters

None.

Returns

Nothing.

Requires

CF card and CF library must be initialized for file operations. See Cf_Fat_Init.

The file must be previously assigned. See Cf_Fat_Assign.

Example
// open file for writing
Cf_Fat_Rewrite();
Notes

None.

Cf_Fat_Append

Prototype

void Cf_Fat_Append();

Description

Opens currently assigned file for appending. Upon this function execution file pointers will be positioned after the last byte in the file, so any subsequent file writing operation will start from there.

Parameters

None.

Returns

Nothing.

Requires

CF card and CF library must be initialized for file operations. See Cf_Fat_Init.

File must be previously assigned. See Cf_Fat_Assign.

Example
// open file for appending
Cf_Fat_Append();
Notes

None.

Cf_Fat_Delete

Prototype

void Cf_Fat_Delete();

Description

Deletes currently assigned file from CF card.

Parameters

None.

Returns

Nothing.

Requires

CF card and CF library must be initialized for file operations. See Cf_Fat_Init.

File must be previously assigned. See Cf_Fat_Assign.

Example
// delete current file
Cf_Fat_Delete();
Notes

None.

Cf_Fat_Write

Prototype

void Cf_Fat_Write(char *fdata, unsigned data_len);

Description

Writes requested number of bytes to currently assigned file opened for writing.

Parameters
  • fdata: data to be written.
  • data_len: number of bytes to be written.
Returns

Nothing.

Requires

CF card and CF library must be initialized for file operations. See Cf_Fat_Init.

File must be previously assigned. See Cf_Fat_Assign.

File must be open for writing. See Cf_Fat_Rewrite or Cf_Fat_Append.

Example
char file_contents[42];
...
Cf_Fat_Write(file_contents, 42); // write data to the assigned file
Notes

None.

Cf_Fat_Set_File_Date

Prototype

void Cf_Fat_Set_File_Date(unsigned int year, unsigned short month, unsigned short day, unsigned short hours, unsigned short mins, unsigned short seconds);

Description

Sets the date/time stamp. Any subsequent file writing operation will write this stamp to currently assigned file's time/date attributes.

Parameters
  • year: year attribute. Valid values: 1980-2107
  • month: month attribute. Valid values: 1-12
  • day: day attribute. Valid values: 1-31
  • hours: hours attribute. Valid values: 0-23
  • mins: minutes attribute. Valid values: 0-59
  • seconds: seconds attribute. Valid values: 0-59
Returns

Nothing.

Requires

CF card and CF library must be initialized for file operations. See Cf_Fat_Init.

File must be previously assigned. See Cf_Fat_Assign.

File must be open for writing. See Cf_Fat_Rewrite or Cf_Fat_Append.

Example
Cf_Fat_Set_File_Date(2005,9,30,17,41,0);
Notes

None.

Cf_Fat_Get_File_Date

Prototype

void Cf_Fat_Get_File_Date(unsigned int *year, unsigned short *month, unsigned short *day, unsigned short *hours, unsigned short *mins);

Description

Reads time/date attributes of currently assigned file.

Parameters
  • year: buffer to store year attribute to. Upon function execution year attribute is returned through this parameter.
  • month: buffer to store month attribute to. Upon function execution month attribute is returned through this parameter.
  • day: buffer to store day attribute to. Upon function execution day attribute is returned through this parameter.
  • hours: buffer to store hours attribute to. Upon function execution hours attribute is returned through this parameter.
  • mins: buffer to store minutes attribute to. Upon function execution minutes attribute is returned through this parameter.
Returns

Nothing.

Requires

CF card and CF library must be initialized for file operations. See Cf_Fat_Init.

File must be previously assigned. See Cf_Fat_Assign.

Example
unsigned year;
char month, day, hours, mins;
...
Cf_Fat_Get_File_Date(&year, &month, &day, &hours, &mins);
Notes

None.

Cf_Fat_Get_File_Date_Modified

Prototype

void Cf_Fat_Get_File_Date_Modified(unsigned int *year, unsigned short *month, unsigned short *day, unsigned short *hours, unsigned short *mins);

Description

Retrieves the last modification date/time of the currently assigned file.

Parameters
  • year: buffer to store year of modification attribute to. Upon function execution year of modification attribute is returned through this parameter.
  • month: buffer to store month of modification attribute to. Upon function execution month of modification attribute is returned through this parameter.
  • day: buffer to store day of modification attribute to. Upon function execution day of modification attribute is returned through this parameter.
  • hours: buffer to store hours of modification attribute to. Upon function execution hours of modification attribute is returned through this parameter.
  • mins: buffer to store minutes of modification attribute to. Upon function execution minutes of modification attribute is returned through this parameter.
Returns

Nothing.

Requires

CF card and CF library must be initialized for file operations. See Cf_Fat_Init.

File must be previously assigned. See Cf_Fat_Assign.

Example
unsigned year;
char month, day, hours, mins;
...
Cf_Fat_Get_File_Date_Modified(&year, &month, &day, &hours, &mins);
Notes

None.

Cf_Fat_Get_File_Size

Prototype

unsigned long Cf_Fat_Get_File_Size();

Description

This function reads size of currently assigned file in bytes.

Parameters

None.

Returns

Size of the currently assigned file in bytes.

Requires

CF card and CF library must be initialized for file operations. See Cf_Fat_Init.

File must be previously assigned. See Cf_Fat_Assign.

Example
unsigned long my_file_size;
...
my_file_size = Cf_Fat_Get_File_Size();
Notes

None.

Cf_Fat_Get_Swap_File

Prototype

unsigned long Cf_Fat_Get_Swap_File(unsigned long sectors_cnt, char *filename, char file_attr);

Description

This function is used to create a swap file of predefined name and size on the CF media. If a file with specified name already exists on the media, search for consecutive sectors will ignore sectors occupied by this file. Therefore, it is recommended to erase such file if it exists before calling this function. If it is not erased and there is still enough space for a new swap file, this function will delete it after allocating new memory space for a new swap file.

The purpose of the swap file is to make reading and writing to CF media as fast as possible, by using the Cf_Read_Sector() and Cf_Write_Sector() functions directly, without potentially damaging the FAT system. Swap file can be considered as a "window" on the media where the user can freely write/read data. It's main purpose in the this library is to be used for fast data acquisition; when the time-critical acquisition has finished, the data can be re-written into a "normal" file, and formatted in the most suitable way.

Parameters
  • sectors_cnt: number of consecutive sectors that user wants the swap file to have.
  • filename: name of the file that should be assigned for file operations. The file name should be in DOS 8.3 (file_name.extension) format. The file name and extension will be automatically padded with spaces by the library if they have less than length required (i.e. "mikro.tx" -> "mikro .tx "), so the user does not have to take care of that. The file name and extension are case insensitive. The library will convert them to proper case automatically, so the user does not have to take care of that.

    Also, in order to keep backward compatibility with the first version of this library, file names can be entered as UPPERCASE string of 11 bytes in length with no dot character between the file name and extension (i.e. "MIKROELETXT" -> MIKROELE.TXT). In this case the last 3 characters of the string are considered to be file extension.

  • file_attr: file creation and attributes flags. Each bit corresponds to the appropriate file attribute:
  • Bit Mask Description
    0 0x01 Read Only
    1 0x02 Hidden
    2 0x04 System
    3 0x08 Volume Label
    4 0x10 Subdirectory
    5 0x20 Archive
    6 0x40 Device (internal use only, never found on disk)
    7 0x80 Not used

Returns

  • Number of the start sector for the newly created swap file, if there was enough free space on CF card to create file of required size.
  • 0 - otherwise.

Requires

CF card and CF library must be initialized for file operations. See Cf_Fat_Init.

Example
//-------------- Try to create a swap file with archive atribute, whose size will be at least 1000 sectors.
//               If it succeeds, it sends the No. of start sector over UART
unsigned long size;
...
size = Cf_Fat_Get_Swap_File(1000, "mikroE.txt", 0x20);
if (size) {
  UART1_Write(0xAA);
  UART1_Write(Lo(size));
  UART1_Write(Hi(size));
  UART1_Write(Higher(size));
  UART1_Write(Highest(size));
  UART1_Write(0xAA);
}
Notes Long File Names (LFN) are not supported.

Library Example

The following example writes 512 bytes at sector no.620, and then reads the data and sends it over UART1 for a visual check. Hardware configurations in this example are made for the LV-32MX v6 development system and PIC32MX460F512L.

Copy Code To ClipboardCopy Code To Clipboard
// set compact flash pinout
char Cf_Data_Port at PORTE;

sbit CF_RDY at RD7_bit;
sbit CF_WE  at LATD6_bit;  // for writing to output pin always use latch
sbit CF_OE  at LATD5_bit;  // for writing to output pin always use latch
sbit CF_CD1 at RD4_bit;
sbit CF_CE1 at LATD3_bit;  // for writing to output pin always use latch
sbit CF_A2  at LATD2_bit;  // for writing to output pin always use latch
sbit CF_A1  at LATD1_bit;  // for writing to output pin always use latch
sbit CF_A0  at LATD0_bit;  // for writing to output pin always use latch

sbit CF_RDY_direction at TRISD7_bit;
sbit CF_WE_direction  at TRISD6_bit;
sbit CF_OE_direction  at TRISD5_bit;
sbit CF_CD1_direction at TRISD4_bit;
sbit CF_CE1_direction at TRISD3_bit;
sbit CF_A2_direction  at TRISD2_bit;
sbit CF_A1_direction  at TRISD1_bit;
sbit CF_A0_direction  at TRISD0_bit;
// end of cf pinout

const LINE_LEN = 39;
char err_txt[20]       = "FAT16 not found";
char file_contents[LINE_LEN] = "XX CF FAT16 library by Anton Rieckert\n";
char           filename[14] = "MIKRO00x.TXT";          // File names
unsigned short loop, loop2;
unsigned long  i, size;
char           Buffer[512];

// UART1 write text and new line (carriage return + line feed)
void UART1_Write_Line(char *uart_text) {
  UART1_Write_Text(uart_text);
  UART1_Write(13);
  UART1_Write(10);
}

// Creates new file and writes some data to it
void M_Create_New_File() {
  filename[7] = 'A';
  Cf_Fat_Set_File_Date(2005,6,21,10,35,0);             // Set file date & time info
  Cf_Fat_Assign(&filename, 0xA0);                      // Find existing file or create a new one
  Cf_Fat_Rewrite();                                    // To clear file and start with new data
  for(loop = 1; loop <= 99; loop++) {
    UART1_Write('.');
    file_contents[0] = loop / 10 + 48;
    file_contents[1] = loop % 10 + 48;
    Cf_Fat_Write(file_contents, LINE_LEN-1);           // write data to the assigned file
  }
}

// Creates many new files and writes data to them
void M_Create_Multiple_Files() {
  for(loop2 = 'B'; loop2 <= 'Z'; loop2++) {
    UART1_Write(loop2);                                // signal the progress
    filename[7] = loop2;                               // set filename
    Cf_Fat_Set_File_Date(2005,6,21,10,35,0);           // Set file date & time info
    Cf_Fat_Assign(&filename, 0xA0);                    // find existing file or create a new one
    Cf_Fat_Rewrite();                                  // To clear file and start with new data
    for(loop = 1; loop <= 44; loop++) {
      file_contents[0] = loop / 10 + 48;
      file_contents[1] = loop % 10 + 48;
      Cf_Fat_Write(file_contents, LINE_LEN-1);         // write data to the assigned file
    }
  }
}

// Opens an existing file and rewrites it
void M_Open_File_Rewrite() {
  filename[7] = 'C';
  Cf_Fat_Assign(&filename, 0);
  Cf_Fat_Rewrite();
  for(loop = 1; loop <= 55; loop++) {
    file_contents[0] = loop / 10 + 48;
    file_contents[1] = loop % 10 + 48;
    Cf_Fat_Write(file_contents, LINE_LEN-1);           // write data to the assigned file
  }
}

// Opens an existing file and appends data to it
//               (and alters the date/time stamp)
void M_Open_File_Append() {
   filename[7] = 'B';
   Cf_Fat_Assign(&filename, 0);
   Cf_Fat_Set_File_Date(2009, 1, 23, 17, 22, 0);
   Cf_Fat_Append();                                    // Prepare file for append
   Cf_Fat_Write(" for mikroElektronika 2009\n", 27);   // Write data to assigned file
}

// Opens an existing file, reads data from it and puts it to UART
void M_Open_File_Read() {
  char character;

  filename[7] = 'B';
  Cf_Fat_Assign(&filename, 0);
  Cf_Fat_Reset(&size);             // To read file, procedure returns size of file
  for (i = 1; i <= size; i++) {
    Cf_Fat_Read(&character);
    UART1_Write(character);        // Write data to UART
  }
}

// Deletes a file. If file doesn't exist, it will first be created
// and then deleted.
void M_Delete_File() {
  filename[7] = 'F';
  Cf_Fat_Assign(filename, 0);
  Cf_Fat_Delete();
}

// Tests whether file exists, and if so sends its creation date
// and file size via UART
void M_Test_File_Exist() {
  unsigned long  fsize;
  unsigned int   year;
  unsigned short month, day, hour, minute;
  unsigned char  outstr[12];

  filename[7] = 'B';       //uncomment this line to search for file that DOES exists
//  filename[7] = 'F';       //uncomment this line to search for file that DOES NOT exist
  if (Cf_Fat_Assign(filename, 0)) {
    //--- file has been found - get its date
    Cf_Fat_Get_File_Date(&year, &month, &day, &hour, &minute);
    UART1_Write_Text(" created: ");
    WordToStr(year, outstr);
    UART1_Write_Text(outstr);
    ByteToStr(month, outstr);
    UART1_Write_Text(outstr);
    WordToStr(day, outstr);
    UART1_Write_Text(outstr);
    WordToStr(hour, outstr);
    UART1_Write_Text(outstr);
    WordToStr(minute, outstr);
    UART1_Write_Text(outstr);

    //--- file has been found - get its modified date
    Cf_Fat_Get_File_Date_Modified(&year, &month, &day, &hour, &minute);
    UART1_Write_Text(" modified: ");
    WordToStr(year, outstr);
    UART1_Write_Text(outstr);
    ByteToStr(month, outstr);
    UART1_Write_Text(outstr);
    WordToStr(day, outstr);
    UART1_Write_Text(outstr);
    WordToStr(hour, outstr);
    UART1_Write_Text(outstr);
    WordToStr(minute, outstr);
    UART1_Write_Text(outstr);

    //--- get file size
    fsize = Cf_Fat_Get_File_Size();
    LongToStr((signed long)fsize, outstr);
    UART1_Write_Line(outstr);
  }
  else {
    //--- file was not found - signal it
    UART1_Write(0x55);
    Delay_ms(1000);
    UART1_Write(0x55);
  }
}


// Tries to create a swap file, whose size will be at least 100
// sectors (see Help for details)
void M_Create_Swap_File() {
  unsigned int i;

  for(i=0; i<512; i++)
    Buffer[i] = i;

  size = Cf_Fat_Get_Swap_File(5000, "mikroE.txt", 0x20);   // see help on this function for details

  if (size) {
    LongToStr((signed long)size, err_txt);
    UART1_Write_Line(err_txt);

    for(i=0; i<5000; i++) {
      Cf_Write_Sector(size++, Buffer);
      UART1_Write('.');
    }
  }
}

// Main. Uncomment the function(s) to test the desired operation(s)
void main() {
  #define COMPLETE_EXAMPLE            // comment this line to make simpler/smaller example
  CHECON = 0x32;
  AD1PCFG = 0xFFFF;                   // disable A/D inputs

  // Initialize UART1 module
  UART1_Init(56000);
  Delay_ms(10);

  UART1_Write_Line("MCU-Started");    // MCU present report

  // use fat16 quick format instead of init routine if a formatting is needed
  if (Cf_Fat_Init() == 0) {
    Delay_ms(2000);                   // wait for a while until the card is stabilized
                                      //   period depends on used CF card
    //--- Test start
    UART1_Write_Line("Test Start.");
    //--- Test routines. Uncomment them one-by-one to test certain features
    M_Create_New_File();
    #ifdef COMPLETE_EXAMPLE
      M_Create_Multiple_Files();
      M_Open_File_Rewrite();
      M_Open_File_Append();
      M_Open_File_Read();
      M_Delete_File();
      M_Test_File_Exist();
      M_Create_Swap_File();
    #endif
    UART1_Write_Line("Test End.");
  }
  else {
    UART1_Write_Line(err_txt); // Note: Cf_Fat_Init tries to initialize a card more than once.
                               //       If card is not present, initialization may last longer (depending on clock speed)
  }
}

HW Connection

Pin diagram of CF memory card

Pin diagram of CF memory card

Copyright (c) 2002-2012 mikroElektronika. All rights reserved.
What do you think about this topic ? Send us feedback!
Want more examples and libraries? 
Find them on LibStock - A place for the code