Picproje Elektronik Sitesi

DERLEYİCİLER => MikroC - PIC => MikroC ARM => Konuyu başlatan: Karamel - 02 Ağustos 2015, 01:01:58

Başlık: mikroc fat library
Gönderen: Karamel - 02 Ağustos 2015, 01:01:58
merhaba. tft ekranimi bozunca bende mmc deneyi yapayim dedim. sabah birkac saat ugrastim ama basarili olamadim. oncelikle adim adim gidip. meseleyi anlamak istiyorum. help file deki example fat16 destekliyor. suradaki http://www.libstock.com/projects/view/108/fat32-library (http://www.libstock.com/projects/view/108/fat32-library) fat32 file bicimini destekliyor ama simdilik buna bulasmiyayim dedim.

windows ta 1gb lik microsd card imi bicimlendirmek isteyince karsima boyle bir tablo cikiyor. burada fat 16 yok? ayrica dosya ara birimi diye(sanirim bu sector size) kb yada byte seklinde tanimlanmis secenekler var. sanirin bunuda 512 secmem gerekli?

(http://i.hizliresim.com/d22V4Z.png) (http://hizliresim.com/d22V4Z)


daha sonra code umuza bakacak olursak.

mmc_chip_select ucunu pa15 olarak sectim. spi ara birimide spi3 yani pb3-4-5 olarak sectim. uart baglantim olmadigi icin ne gibi ciktilar geliyor goremiyorum.

sanirim asagidaki code mmc card icersinde bir dosya olusturmasi gerekli?

// MMC module connections
sbit Mmc_Chip_Select           at GPIOA_ODR.B15;
// eof MMC module connections

const LINE_LEN = 43;

char err_txt[20]             = "FAT16 not found";
char filename[14]            = "MIKRO00x.TXT";          // File names
char file_contents[LINE_LEN] = "XX MMC/SD FAT16 library by Anton Rieckertn";

unsigned long  i, size;
unsigned short loop, loop2;
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';
  Mmc_Fat_Set_File_Date(2011,1,12,11,9,0);   // Set file date & time info
  Mmc_Fat_Assign(&filename, 0xA0);            // Find existing file or create a new one
  Mmc_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;
    Mmc_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
    Mmc_Fat_Set_File_Date(2011,1,12,11,9,0);  // Set file date & time info
    Mmc_Fat_Assign(&filename, 0xA0);          // find existing file or create a new one
    Mmc_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;
      Mmc_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';
  Mmc_Fat_Assign(&filename, 0);
  Mmc_Fat_Rewrite();
  for(loop = 1; loop <= 55; loop++) {
    file_contents[0] = loop / 10 + 48;
    file_contents[1] = loop % 10 + 48;
    Mmc_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';
   Mmc_Fat_Assign(&filename, 0);
   Mmc_Fat_Set_File_Date(2009, 1, 23, 17, 22, 0);
   Mmc_Fat_Append();                                    // Prepare file for append
   Mmc_Fat_Write(" for mikroElektronika 2009n", 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';
  Mmc_Fat_Assign(&filename, 0);
  Mmc_Fat_Reset(&size);            // To read file, procedure returns size of file
  for (i = 1; i <= size; i++) {
    Mmc_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';
  Mmc_Fat_Assign(filename, 0);
  Mmc_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];

  Mmc_Fat_Get_File_Date(&year, &month, &day, &hour, &minute);

  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 (Mmc_Fat_Assign(filename, 0)) {
    //--- file has been found - get its create date
    Mmc_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
    Mmc_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 = Mmc_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 = Mmc_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++) {
      Mmc_Write_Sector(size++, Buffer);
      UART1_Write('.');
    }
  }
}

      unsigned long clk;
//-------------- Main. Uncomment the function(s) to test the desired operation(s)
void main() {
  #define COMPLETE_EXAMPLE               // comment this line to make simpler/smaller example
  // Initialize UART1 module
  UART1_Init(19200);
  Delay_ms(10);

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

  //--- set up SPI for MMC init (low speed)
  SPI3_Init_Advanced(_SPI_FPCLK_DIV64, _SPI_MASTER | _SPI_8_BIT |
                     _SPI_CLK_IDLE_LOW | _SPI_FIRST_CLK_EDGE_TRANSITION |
                     _SPI_MSB_FIRST | _SPI_SS_DISABLE | _SPI_SSM_ENABLE | _SPI_SSI_1,
                     &_GPIO_MODULE_SPI3_PB345);

  Delay_ms(10);

  //--- init the FAT library
  if (!Mmc_Fat_Init()) {
    // reinitialize spi at higher speed
    SPI3_Init_Advanced(_SPI_FPCLK_DIV2, _SPI_MASTER | _SPI_8_BIT |
                       _SPI_CLK_IDLE_LOW | _SPI_FIRST_CLK_EDGE_TRANSITION |
                       _SPI_MSB_FIRST | _SPI_SS_DISABLE | _SPI_SSM_ENABLE | _SPI_SSI_1,
                       &_GPIO_MODULE_SPI3_PB345);
    //--- 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: Mmc_Fat_Init tries to initialize a card more than once.
                               //       If card is not present, initialization may last longer (depending on clock speed)
  }

}
Başlık: Ynt: mikroc fat library
Gönderen: RaMu - 02 Ağustos 2015, 01:13:44
Windows daki FAT seçeneği FAT16 demek.
Birde FAT12 varmış ama hiç rastlamadım.
SD kartı FAT16 biçimlendirdikten sonra
Winhex HxD programı ile içini byte byte görebilirsin.
Sector size ile oynamana gerek yok.

Pic için örnek uygulama ve isis simulasyon linkde var,
benzer tarafları incelenebilir,
mikroc nin help kısmıda iyi oluyor genelde.
https://www.picproje.org/index.php?topic=54274.0 (https://www.picproje.org/index.php?topic=54274.0)
Başlık: Ynt: mikroc fat library
Gönderen: Karamel - 02 Ağustos 2015, 02:49:52
hocam fat(varsayilan) olandan bahsediyorsaniz. sector size lari 16kb ve 32kb seceneklerinden baska bir secenek yok. yani bu secenekte sector sizelarini 512 byte secemiyorum?
Başlık: Ynt: mikroc fat library
Gönderen: tekosis - 02 Ağustos 2015, 03:31:22
karamel hocam eğer mikroc ile tft ekran uygulamalarında hızlı bir sonuç almak istiyorsan visualtft programını incelemeni tavsiye ederim. tabi mikroelektronika'nın kendi geliştirme kartları ile birebir uyumlu ama bu programı kendi tasarımlarında da kullanabilirsin.
Başlık: Ynt: mikroc fat library
Gönderen: Karamel - 02 Ağustos 2015, 03:35:13
hocam tft ekranimi suan kenari biraktim. bread board ta voltage lari karistirinca bozuldu. suan mmc ve i2c eeprom ile deneyler yapiyorum.
Başlık: Ynt: mikroc fat library
Gönderen: tekosis - 02 Ağustos 2015, 03:36:24
kusura bakma saate ver :)
Başlık: Ynt: mikroc fat library
Gönderen: Karamel - 02 Ağustos 2015, 03:38:32
est. ne kusuru hocam :)

sevgiler ::)
Başlık: Ynt: mikroc fat library
Gönderen: RaMu - 02 Ağustos 2015, 14:35:22
512 byte olabilecek olan aslında block size,
sector size ile pek işin yoktur.
Belkide windows un bahsettiği sector size
aslında cluster size dır,
bunun boyutuda senin için pek bir şey değiştirmez.
Bir dosya açıldığında en az cluster size kadar yer kaplar o etkisi olur,
bir dosyanın içeriğini bulurken bazı hileler yapabilmene olanak sağlayabilir
ama bunlarda FAT kütüphanesini kendin yazarsan olur.

Hazır bir FAT kütüphanesi kullanırken, sector size vs. önemli olmamalı,
aslında FAT16 veya FAT32 olmasıda önemli olmamalı ama
kütüphane fazla yer kaplayacağı için burada seçenek baştan sunulmuş,
FAT16 veya FAT32 yi baştan seç diyor kütüphane.
Geri kalan sector size, block size, cluster size,kart block address mi byte address mi vs.
gibi şeyleri, FAT kütüphanesi kartı okuyup kendi bulabilmeli.
Başlık: Ynt: mikroc fat library
Gönderen: engerex - 02 Ağustos 2015, 14:53:51
 Komut satirina Help Format yazarsan detaylari gorebilirsin. Fat, fat32, exfat, NTFS icin bu degerin 512 bayttan basladigini gorebilirsin.
Başlık: Ynt: mikroc fat library
Gönderen: Karamel - 04 Ağustos 2015, 04:10:54
fat16 dan vazgecip daha guncel bir version olan fat32 ile calismalar yapmaya basladim ama bundada sonuc alamadim. microsd card imi fat32 block size = 512 byte seklinde yaptim ama library hep init fail hatasi veriyor.(serial porttan bunu gonderiyor)

su library yi http://www.libstock.com/projects/view/108/fat32-library (http://www.libstock.com/projects/view/108/fat32-library) indirip kurdum. SPI3 u PB3-4-5  e ayarladim. chip select ide pa15 e ayarladim ama sonuc yok. bu arada spi in calistigini logic analyzerim ile gozlemledim.

/*
* Project Name:
    FAT32 Library

* Copyright:
    (c) MikroElektronika, 2011.

* Revision History:
    20110826 - initial release

* Description:
    This simple example demonstrates the use of FAT32 Library
    on SD/MMC cards via SPI hardware interface and folder content
    display via UART module.
    Files and folders are created and removed; files are read,
    written, their content sent to PC via UART.
* Test configuration:
     MCU:             STM32F207VG
                      http://www.st.com/internet/com/TECHNICAL_RESOURCES/TECHNICAL_LITERATURE/DATASHEET/CD00237391.pdf
     Dev.Board:       EasyMx PRO v7 for STM32(R) ARM(R) - ac:MMC
                      http://www.mikroe.com/eng/products/view/852/easymx-pro-v7-for-stm32/
     Oscillator:      HSE-PLL, 120.000MHz
     Ext. Modules:    None.
     SW:              mikroC PRO for ARM
                      http://www.mikroe.com/eng/products/view/752/mikroc-pro-for-arm/
* Notes:
    + Make sure that SD card is properly formatted (to FAT32 file system)
      prior testing it on this example.
    + Turn off all LED switches (SW15) and pull-up/down switches.
    + Connect USB cable to USB UARTA port and turn on Rx and Tx switches:
        - SW12.1 -> ON
        - SW12.2 -> ON
    + Turn on SPI and MMC switches:
        - SW13.1 -> ON
        - SW13.2 -> ON
        - SW13.3 -> ON
        - SW14.3 -> ON
    + Insert the card into MMC-SD module prior usage.
*/

#include "__Lib_FAT32.h"

////////////////////////////////////////////////////////////////////////////////
#define __ARM__
#define DIR_TEST_1
#define DIR_TEST_2
#define FILE_TEST
#define SWAP_TEST

////////////////////////////////////////////////////////////////////////////////
//
//          Mmc Library requirements for different MPU families
//
////////////////////////////////////////////////////////////////////////////////

#ifdef __PIC__
sbit Mmc_Chip_Select           at RC0_bit;
sbit Mmc_Chip_Select_Direction at TRISC0_bit;
#endif

#ifdef __AVR__
sbit Mmc_Chip_Select           at PORTG1_bit;
sbit Mmc_Chip_Select_Direction at DDG1_bit;
#endif

#ifdef __dsPIC__
sbit Mmc_Chip_Select           at LATG9_bit;  // for writing to output pin always use latch
sbit Mmc_Chip_Select_Direction at TRISG9_bit;
#endif

#ifdef __PIC32__
sbit Mmc_Chip_Select           at LATG9_bit;  // for writing to output pin always use latch
sbit Mmc_Chip_Select_Direction at TRISG9_bit;
#endif

#ifdef __ARM__
sbit Mmc_Chip_Select           at GPIOA_ODR.B15;
#endif

////////////////////////////////////////////////////////////////////////////////
//
//          SPI initialization routines required by Mmc Library
//
////////////////////////////////////////////////////////////////////////////////

void initSPI(void)
{
    #ifdef __PIC__
    SPI1_Init_Advanced(_SPI_MASTER_OSC_DIV64, _SPI_DATA_SAMPLE_MIDDLE, _SPI_CLK_IDLE_LOW, _SPI_LOW_2_HIGH);
    #endif
    #ifdef __AVR__
    SPI1_Init_Advanced(_SPI_MASTER, _SPI_FCY_DIV128, _SPI_CLK_LO_LEADING);
    #endif
    #ifdef __dsPIC__
    SPI2_Init_Advanced(_SPI_MASTER, _SPI_8_BIT, _SPI_PRESCALE_SEC_1, _SPI_PRESCALE_PRI_64, _SPI_SS_DISABLE, _SPI_DATA_SAMPLE_MIDDLE, _SPI_CLK_IDLE_HIGH, _SPI_ACTIVE_2_IDLE);
    #endif
    #ifdef __PIC32__
    SPI2_Init_Advanced(_SPI_MASTER, _SPI_8_BIT, 64, _SPI_SS_DISABLE, _SPI_DATA_SAMPLE_MIDDLE, _SPI_CLK_IDLE_HIGH, _SPI_ACTIVE_2_IDLE);
    #endif
    #ifdef __ARM__
    SPI3_Init_Advanced(_SPI_FPCLK_DIV64, _SPI_MASTER | _SPI_8_BIT |
                       _SPI_CLK_IDLE_LOW | _SPI_FIRST_CLK_EDGE_TRANSITION |
                       _SPI_MSB_FIRST | _SPI_SS_DISABLE | _SPI_SSM_ENABLE | _SPI_SSI_1,
                       &_GPIO_MODULE_SPI3_PB345);
    #endif
}

void initFastSPI(void)
{
    #ifdef __PIC__
    SPI1_Init_Advanced(_SPI_MASTER_OSC_DIV4, _SPI_DATA_SAMPLE_MIDDLE, _SPI_CLK_IDLE_LOW, _SPI_LOW_2_HIGH);
    #endif
    #ifdef __AVR__
    SPI1_Init_Advanced(_SPI_MASTER, _SPI_FCY_DIV2, _SPI_CLK_LO_LEADING);
    #endif
    #ifdef __dsPIC__
    SPI2_Init_Advanced(_SPI_MASTER, _SPI_8_BIT, _SPI_PRESCALE_SEC_1, _SPI_PRESCALE_PRI_4, _SPI_SS_DISABLE, _SPI_DATA_SAMPLE_MIDDLE, _SPI_CLK_IDLE_HIGH, _SPI_ACTIVE_2_IDLE);
    #endif
    #ifdef __PIC32__
    SPI2_Init_Advanced(_SPI_MASTER, _SPI_8_BIT, 8, _SPI_SS_DISABLE, _SPI_DATA_SAMPLE_MIDDLE, _SPI_CLK_IDLE_HIGH, _SPI_ACTIVE_2_IDLE);
    #endif
    #ifdef __ARM__
    SPI3_CR1 = 0;

    SPI3_Init_Advanced(_SPI_FPCLK_DIV2, _SPI_MASTER | _SPI_8_BIT |
                       _SPI_CLK_IDLE_LOW | _SPI_FIRST_CLK_EDGE_TRANSITION |
                       _SPI_MSB_FIRST | _SPI_SS_DISABLE | _SPI_SSM_ENABLE | _SPI_SSI_1,
                       &_GPIO_MODULE_SPI3_PB345);
    #endif
}


////////////////////////////////////////////////////////////////////////////////
//
//  many of these messages are not used in the example,
//  as they are intended for future improvement
//
////////////////////////////////////////////////////////////////////////////////

const char cmd[16][16] =
{
    "init           ",    //  0
    "qformat        ",    //  1
    "mkdir          ",    //  2
    "chdir          ",    //  3
    "rmdir          ",    //  4
    "dir            ",    //  5
    "rendir         ",    //  6
    "assign         ",    //  7
    "read           ",    //  8
    "append         ",    //  9
    "rewrite        ",    // 10
    "delete         ",    // 11
    "rename         ",    // 12
    "swap           ",    // 13
    "set date       ",    // 14
    "get date       "     // 15
};

const char cmdOK[16][16] =
{
    "init ok        ",
    "qformat ok     ",
    "mkdir ok       ",
    "chdir ok       ",
    "rmdir ok       ",
    "dir ok         ",
    "rendir ok      ",
    "assign ok      ",
    "read ok        ",
    "append ok      ",
    "rewrite ok     ",
    "delete ok      ",
    "rename ok      ",
    "swap ok        ",
    "set date ok    ",
    "get date ok    "
};

const char cmdFAIL[16][16] =
{
    "init failed    ",
    "qformat failed ",
    "mkdir failed   ",
    "chdir failed   ",
    "rmdir failed   ",
    "dir failed     ",
    "rendir failed  ",
    "assign failed  ",
    "read failed    ",
    "append failed  ",
    "rewrite failed ",
    "delete failed  ",
    "rename failed  ",
    "swap failed    ",
    "set date failed",
    "get date failed"
};

const char len[16] =
{
    4,
    7,
    5,
    5,
    5,
    3,
    6,
    6,
    4,
    6,
    7,
    6,
    6,
    4,
    8,
    8
};

const char line[16]         =   "***************";
const char unknown[16]      =   "unknown command";
const char startOK[16]      =   "init successful";
const char startFAIL[16]    =   "init failed    ";
const char cmdStart[16]     =   "cmd demo start ";
const char noFileName[16]   =   "NO FILE NAME   ";
const char noDirName[16]    =   "NO DIR NAME    ";
const char noVolumeName[16] =   "NO VOLUME NAME ";

////////////////////////////////////////////////////////////////////////////////

int8   err;
uint8  i, j, attr;
uint16 cnt, bpcl;
uint32 k;
uint32 size;
uint32 totalClusts,
       freeClusts,
       badClusts;

__TIME tm;
__SECTOR sc;
__HANDLE fileHandle[4];

char ch;
char DirName[9];
char FileName[13];
char uartbuf[32];
char del[2] = "\r";

char rdbuf[19] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '};
char wrbuf[15] = {'[', '+', ']', '-', '-', '-', '+', '+', '+', '=', '=', '=', '~', '~', '~'};

#ifdef SWAP_TEST
char buff[512];
#endif

////////////////////////////////////////////////////////////////////////////////

static char* constToVar(char *dst, const char *src)
{
    char *tmp;

    tmp = dst;
    for (;;)
    {
        *dst = *src;
        if (*src == 0) break;
        src++;
        dst++;
    }
    return tmp;
}

////////////////////////////////////////////////////////////////////////////////

/*char iscmd(char n)
{
    if (0 == memcmp(uartbuf, constToVar(varbuf, cmd[n]), len[n]))
        return 1;
    else
        return 0;
}*/

////////////////////////////////////////////////////////////////////////////////

void UART_Write_ConstText(const char *text)
{
    UART_Write_Text(constToVar(uartbuf, text));
}

////////////////////////////////////////////////////////////////////////////////
//
// main program
//
////////////////////////////////////////////////////////////////////////////////
void main(void)
{
    #ifdef __PIC__
    ANSELC = 0;                            // Configure AN pins as digital
    SLRCON = 0;                            // Set output slew rate on all ports at standard rate
    #endif

    #ifdef __AVR__
    #endif

    #ifdef __dsPIC__
    ADPCFG = 0xFFFF;                       // configure AN pins as digital I/O
    #endif

    #ifdef __PIC32__
    ///////////////////////////////////////
    // Disable MX4 rf module (shares spi lines with mmc/sd slot)
    //  TRISD8_bit = 0;                      // RF-CS
    //  LATD8_bit = 1;                       // Not selected
    ///////////////////////////////////////

    AD1PCFG = 0xFFFF;                      // configure AN pins as digital I/O
    #endif

    ///////////////////////////////////////
    //  UART module initialization
    ///////////////////////////////////////
    #ifdef __ARM__
    UART4_Init(9600);
    GPIO_Digital_Output(&GPIOA_BASE, _GPIO_PINMASK_8);
    GPIOA_ODR.F8 = 1;
    #else
    UART4_Init(9600);
    #endif
    #ifdef __dsPIC__
    // U1MODEbits.ALTIO = 1;
    #endif
    Delay_ms(100);

    UART_Write(CR);
    UART_Write_ConstText(line);
    UART_Write(CR);
    Delay_ms(100);

    ///////////////////////////////////////
    //  SPI module initialization
    ///////////////////////////////////////
    initSPI();

    ///////////////////////////////////////
    //  initialize storage device.
    //  optionally, we could format the device
    //  instead of just initializing it.
    ///////////////////////////////////////
    err = FAT32_Init();
    // err = FAT32_format("dev0");
    if (err < 0)        //
    {
        UART_Write(CR);
        UART_Write_Text(constToVar(uartbuf, cmdFAIL[0]));
        UART_Write(CR);

        while(err < 0)  //  ...retry each second
        {
            err = FAT32_Init();
            Delay_ms(1000);
        }
    }
    ///////////////////////////////////////
    //  if all went well, reinitialize
    //  SPI with greater speed
    ///////////////////////////////////////
    initFastSPI();
    UART_Write(CR);
    UART_Write_Text(constToVar(uartbuf, cmdOK[0]));
    UART_Write(CR);

    err = FAT32_Dir();
    UART_Write(CR);

    ////////////////////////////////////////////////////////////////////////////
    //
    //  In this section folder operation is demonstrated:
    //      - folder creation (all files are left empty, however)
    //      - entering in and out of a folder
    //      - removal of a folder and it's contents
    //      - display of folder contents
    //
    ////////////////////////////////////////////////////////////////////////////
    #ifdef DIR_TEST_1
    {
        tm.Year   = 2011;       // initialize time ...
        tm.Month  = 8;
        tm.Day    = 11;
        tm.Hour   = 16;
        tm.Minute = 20;
        tm.Second = 11;

        FAT32_SetTime(&tm);     // ...and set global time stamps
        FAT32_IncTime(2*60*60 + 30*60 + 40);   // increment time stamp by 2 hours, 30 minutes and 40 seconds

        err = 0;
        memset(DirName, 0, 9);
        for (i = 'A'; i <= 'Z'; i++)
        {
            memcpy (DirName, "DIR_", 5);
            DirName[3] = i;

            err = FAT32_MakeDir(DirName);
            err = FAT32_ChangeDir(DirName);
            for (j = 'A'; j <= 'Z'; j++)
            {
                FAT32_IncTime(20*60 + 10);      // increment time stamp some more
                memcpy(FileName, "FILE__.TXT", 11);
                FileName[4] = i;
                FileName[5] = j;
                fileHandle[0] = FAT32_Open(FileName, FILE_APPEND);
                if (fileHandle[0] < 0)
                {
                    UART_Write(i);
                    UART_Write(j);
                    while(1);
                }
                err = FAT32_Close(fileHandle[0]);

                // get create and modification time stamps
                // they should be 20*60 + 10 seconds apart
                FAT32_getCTime(FileName, &tm);
                FAT32_getMTime(FileName, &tm);
            }
            {
                FAT32_IncTime(20*60 + 10);
                err = FAT32_MakeDir("DIRX");
                err = FAT32_Dir();
                UART_Write(CR);
                err = FAT32_ChangeDir("DIRX");
                fileHandle[0] = FAT32_Open("FILEX.TXT", FILE_WRITE);
                if (fileHandle[0] < 0)
                {
                    UART_Write(i);
                    UART_Write(j);
                    while(1);
                }
                err = FAT32_Close(fileHandle[0]);
                //err = FAT32_ChangeDir("..");
                err = FAT32_Dir();
                UART_Write(CR);
                err = FAT32_ChangeDir("\\"); // get back to the root directory.
            }
            //err = FAT32_ChangeDir("..");
            err = FAT32_Dir();
            UART_Write(CR);
        }
        for (i = 'A'; i <= 'Z'; i++)
        {
            memcpy (DirName, "DIR_", 5);
            DirName[3] = i;
            err = FAT32_DeleteRec(DirName);
            err = FAT32_Dir();
            UART_Write(CR);
        }
        err = FAT32_Dir();
        UART_Write(CR);
    }
    #endif

    ////////////////////////////////////////////////////////////////////////////
    //
    //  In this section creation and removal of a deep directory tree
    //  is demonstrated
    //
    ////////////////////////////////////////////////////////////////////////////
    #ifdef DIR_TEST_2
    {
        tm.Year   = 2011;
        tm.Month  = 8;
        tm.Day    = 20;
        tm.Hour   = 12;
        tm.Minute = 40;
        tm.Second = 29;

        FAT32_SetTime(&tm);
        FAT32_IncTime(1282);

        err = 0;
        memset(DirName, 0, 9);
        for (i = 'A'; i <= 'Z'; i++)
        {
            memcpy (DirName, "DIR_", 5);
            DirName[3] = i;

            err = FAT32_MakeDir(DirName);
            err = FAT32_Dir();
            UART_Write(CR);
            err = FAT32_ChangeDir(DirName);
            for (j = 'A'; j <= 'Z'; j++)
            {
                memcpy(FileName, "FILE__.TXT", 11);
                FileName[4] = i;
                FileName[5] = j;
                fileHandle[0] = FAT32_Open(FileName, FILE_APPEND);
                if (fileHandle[0] < 0)
                {
                    UART_Write(i);
                    UART_Write(j);
                    while(1);
                }
                err = FAT32_Close(fileHandle[0]);
            }
        }
        for (i = 'A';;)
        {
            memcpy (DirName, "DIR_", 5);
            DirName[3] = i;
            err = FAT32_ChangeDir("\\"); // get back to the root directory.
            err = FAT32_Dir();
            UART_Write(CR);
            err = FAT32_DeleteRec(DirName);
            err = FAT32_Dir();
            UART_Write(CR);
            break;
        }
    }
    #endif

    ////////////////////////////////////////////////////////////////////////////
    //
    //  In this section file operation is demonstrated:
    //      - read,
    //      - write,
    //      - append,
    //      - removal.
    //  User might wish to try seek, rename, etc.
    //
    ////////////////////////////////////////////////////////////////////////////
    #ifdef FILE_TEST
    {
        // open some files
        fileHandle[0] = FAT32_Open("FILE1.TXT", FILE_WRITE);
        fileHandle[1] = FAT32_Open("FILE2.TXT", FILE_APPEND);
        fileHandle[2] = FAT32_Open("FILE3.TXT", FILE_APPEND);
        fileHandle[3] = FAT32_Open("FILE4.TXT", FILE_APPEND);

        if (fileHandle[0] < 0) while(1);
        if (fileHandle[1] < 0) while(1);
        if (fileHandle[2] < 0) while(1);
        if (fileHandle[3] < 0) while(1);

        {
            for (k = 0; k < 1000; k++)
            {
                err = FAT32_Write(fileHandle[0], wrbuf, sizeof(wrbuf));
            }
            UART_Write(CR);
            err = FAT32_Close(fileHandle[0]);
        }
        err = FAT32_Dir();
        UART_Write(CR);

        fileHandle[0] = FAT32_Open("FILE1.TXT", FILE_READ);
        if (fileHandle[0] < 0) while(1);

        err = FAT32_Size("FILE1.TXT", &size);
        for (k = 0; k < size;)
        {
            err = FAT32_Read(fileHandle[0], rdbuf, sizeof(rdbuf));
            for (cnt = 0; cnt < sizeof(rdbuf); cnt++, k++)
            {
                if (k < size)
                {
                    UART_Write(rdbuf[cnt]);
                }
                else
                {
                    break;
                }
            }
        }
        UART_Write(CR);
        UART_Write(CR);


        FAT32_Seek(fileHandle[0], 0);   // reset file cursor to 0.
        // FAT32_Seek(fileHandle[0], 5789); // it can be changed to anywhere within a file.

        // read 'rdlen' bytes in "FILE1.TXT" from the position set by FAT32_Seek()
        // and write them to "FILE2.TXT" and "FILE3.TXT"
        err = FAT32_Read (fileHandle[0], rdbuf, sizeof(rdbuf));
        err = FAT32_Write(fileHandle[1], rdbuf, sizeof(rdbuf));
        err = FAT32_Write(fileHandle[2], rdbuf, sizeof(rdbuf));

        // read 3x'rdlen' bytes in "FILE1.TXT" from the current position
        // and write them to "FILE4.TXT"
        err = FAT32_Read (fileHandle[0], rdbuf, sizeof(rdbuf));
        err = FAT32_Write(fileHandle[3], rdbuf, sizeof(rdbuf));
        err = FAT32_Read (fileHandle[0], rdbuf, sizeof(rdbuf));
        err = FAT32_Write(fileHandle[3], rdbuf, sizeof(rdbuf));
        err = FAT32_Read (fileHandle[0], rdbuf, sizeof(rdbuf));
        err = FAT32_Write(fileHandle[3], rdbuf, sizeof(rdbuf));

        // close all opened files
        err = FAT32_Close(fileHandle[0]);
        err = FAT32_Close(fileHandle[1]);
        err = FAT32_Close(fileHandle[2]);
        err = FAT32_Close(fileHandle[3]);

        // display new info on modified files.
        // the info is updated only after file closure.
        err = FAT32_Dir();
        UART_Write(CR);

        // change attribute "FILE1.TXT"
        err = FAT32_GetAttr("FILE1.TXT", &attr);
        err = FAT32_SetAttr("FILE1.TXT", attr | ATTR_HIDDEN);

        err = FAT32_Dir();
        UART_Write(CR);
    }
    #endif

    ////////////////////////////////////////////////////////////////////////
    //
    //  In this section creation of a swap file is demonstrated.
    //  'sc' variable points to the 1st sector of the swap file,
    //  if the user needs access to it via readSector and writeSector
    //  routines.
    //
    ////////////////////////////////////////////////////////////////////////
    #ifdef SWAP_TEST
    {
        // delete already existing swap file
        if (FAT32_Exists("SWAP.TXT"))
        {
            UART_Write_Text("Deleting existing swap file...");
            UART_Write(CR);
            FAT32_Delete("SWAP.TXT");
            err = FAT32_Dir();
            UART_Write(CR);
        }
       
        UART_Write_Text("Creating new swap file...");
        UART_Write(CR);
        err = FAT32_MakeSwap("SWAP.TXT", 500, &sc);  // if swap file creation was successful,
                                                        // we can access it with
        fileHandle[0] = FAT32_Open("SWAP.TXT", FILE_READ);
        if (fileHandle[0] < 0) while(1);

        err = FAT32_Close(fileHandle[0]);
       
        err = FAT32_Dir();
        UART_Write(CR);

        // fill swap file using sector based access
        if (sc) {
          UART_Write_Text("Fill swap file using sector based access...");
          UART_Write(CR);
          UART_Write_Text("Start sector:");
          LongWordToStr(sc, uartbuf);
          UART_Write_Text(uartbuf);
          UART_Write(CR);
          for(cnt=0; cnt<512; cnt++)
            buff[cnt] = cnt;

          for(k=0; k<500; k++) {
            FAT32_Dev_Write_Sector(sc++, buff);
            UART_Write('.');
          }
          UART_Write(CR);
        }

        err = FAT32_Dir();
        UART_Write(CR);
    }
    #endif

    UART_Write(CR);
    FAT32_GetFreeSpace(&freeClusts, &bpcl);
    UART_Write_Text("Free Space Info:");
    UART_Write(CR);
    UART_Write_Text("Free clusters: ");
    LongWordToStr(freeClusts, uartbuf);
    UART_Write_Text(uartbuf);
    UART_Write(CR);
    UART_Write_Text("Free bytes: ");
    LongWordToStr(freeClusts*bpcl, uartbuf);
    UART_Write_Text(uartbuf);
    UART_Write(CR);

    UART_Write(CR);
    FAT32_ScanDisk(&totalClusts, &freeClusts, &badClusts);
    UART_Write_Text("Scan Disk Info:");
    UART_Write(CR);
    UART_Write_Text("Total clusters: ");
    LongWordToStr(totalClusts, uartbuf);
    UART_Write_Text(uartbuf);
    UART_Write(CR);
    UART_Write_Text("Free clusters: ");
    LongWordToStr(freeClusts, uartbuf);
    UART_Write_Text(uartbuf);
    UART_Write(CR);
    UART_Write_Text("Bad clusters: ");
    LongWordToStr(badClusts, uartbuf);
    UART_Write_Text(uartbuf);
    UART_Write(CR);

    UART_Write(CR);
    UART_Write_Text(constToVar(uartbuf, line));
    UART_Write(CR);
}
Başlık: Ynt: mikroc fat library
Gönderen: RaMu - 04 Ağustos 2015, 09:15:05
Bazı mikro sd kartlar spi modu desteklemiyormuş.
Programa bakmadım, problem başka yerdede olabilir,
ama kolay olan başka sd kart ile denemek.
SD karta 3.3V dan fazla vermiyorsun değil mi?

mesaj birleştirme:: 04 Ağustos 2015, 09:16:05

Birde sd karta 100-200mA sağlaman lazım,
yoksa yine problem çıkabilir.

mesaj birleştirme:: 04 Ağustos 2015, 09:17:51

@z Hocanın bloğundaki ve forumdaki sd kartla ilgili yazısınıda okumalısın.
Başlık: Ynt: mikroc fat library
Gönderen: Karamel - 04 Ağustos 2015, 09:25:20
hocam z hocamin yazilarini okudum ama onlar benim anlayabilecegim seviyenin cok uzerinde. bende ne yazik ki anlamamistim...

hocam bu arada sorunu cozdum!!!! :) sorun st arm cortex m3 micro controllerlarin jtag portunun oldugu pinler normal sekilde output edilemiyorlarmis. jtag i disable etmek gerekiyormus. mikroc de bu etki library ile soyle ortadan kaldiriliyor.

GPIO_Alternate_Function_Enable(&_GPIO_MODULE_SWJ_JTAGDISABLE);

bunu yapinca. microcontroller yeniden programlanabiliyor(after reset enable olmali!) jtag pinleride digital IO olarak kullanilabiliyor. benim pa15 jitag portuna denk geldiginden microsd card imin CS ucunu kontrol edemiyormusum. bread board ta pin i degistirince sorunun bu oldugunu anladim. sonra ra15 i neden control edemedigimi anlamaya calistim. sorun hemen ortaya cikti ::)