FATFS con PIC18

Hola a todos,

Le comparto un archivo donde viene el codigo para MPLABX usanado XC8 y el MCC junto con la libreria de FATfs, por ahora estoy usando un microcontrolador PIC18F26K80,solo he creado un archivo de excel delimitado por comas y me funciona muy bien ya solo es seguir el manual de FATfs (ultima version) para realizar otras cosas.

Estuve un semana investigando de como usar el FATfs y por fin funciono, y se los comparto para que no batallen como yo, aunque si estuvo facil la implementacion teniendo ya las librerias adecuadas fue un rollo que pudiera compilar y que funcionara.

Nota:
La memoria que estuve usando es una SANDISK de 8GB. :eek:

Para poder abrirlo necesitas por supuesto la ultima version de XC8 y MPLABX ultima version.

Código:
/**
  Generated Main Source File

  Company:
    Microchip Technology Inc.

  File Name:
    main.c

  Summary:
    This is the main file generated using PIC10 / PIC12 / PIC16 / PIC18 MCUs 

  Description:
    This header file provides implementations for driver APIs for all modules selected in the GUI.
    Generation Information :
        Product Revision  :  PIC10 / PIC12 / PIC16 / PIC18 MCUs  - 1.45
        Device            :  PIC18F26K80
        Driver Version    :  2.00
    The generated drivers are tested against the following:
        Compiler          :  XC8 1.35
        MPLAB             :  MPLAB X 3.40
*/

/*
    (c) 2016 Microchip Technology Inc. and its subsidiaries. You may use this
    software and any derivatives exclusively with Microchip products.

    THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
    EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED
    WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A
    PARTICULAR PURPOSE, OR ITS INTERACTION WITH MICROCHIP PRODUCTS, COMBINATION
    WITH ANY OTHER PRODUCTS, OR USE IN ANY APPLICATION.

    IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE,
    INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND
    WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS
    BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE
    FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN
    ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY,
    THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE.

    MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE
    TERMS.
*/

#include "mcc_generated_files/mcc.h"


/* Private variables ---------------------------------------------------------*/
FATFS fs;         /* Work area (file system object) for logical drive */
FIL fsrc;         /* file objects */   
FRESULT res;
UINT br;

char path[512]="0:";
const uint8_t textFileBuffer[] = "TITULO,NOMBRE,APELLIDOS\t";   

/*******************************************************************************
* Function Name  : SD_TotalSize
* Description    : Îļþ¿Õ¼äÕ¼ÓÃÇé¿ö
* Input          : None
* Output         : None
* Return         : ·µ»Ø1³É¹¦ ·µ»Ø0ʧ°Ü
* Attention		 : None
*******************************************************************************/
int SD_TotalSize(void)
{
    FATFS *fs;
    DWORD fre_clust;        

    res = f_getfree("0:", &fre_clust, &fs);  /* ±ØÐëÊǸùĿ¼£¬Ñ¡Ôñ´ÅÅÌ0 */
    if ( res==FR_OK ) 
    {
	  /* Print free space in unit of MB (assuming 512 bytes/sector) */
      printf("\r\n%d MB total drive space.\r\n"
           "%d MB available.\r\n",
           ( (fs->n_fatent - 2) * fs->csize ) / 2 /1024 , (fre_clust * fs->csize) / 2 /1024 );
		
	  return 1;
	}
	else 
	  return 0;   
}	
/*
                         Main application
 */
void main(void)
{

    // Initialize the device
    SYSTEM_Initialize();

    // If using interrupts in PIC18 High/Low Priority Mode you need to enable the Global High and Low Interrupts
    // If using interrupts in PIC Mid-Range Compatibility Mode you need to enable the Global and Peripheral Interrupts
    // Use the following macros to:

    // Enable high priority global interrupts
    //INTERRUPT_GlobalInterruptHighEnable();

    // Enable low priority global interrupts.
    //INTERRUPT_GlobalInterruptLowEnable();

    // Disable high priority global interrupts
    //INTERRUPT_GlobalInterruptHighDisable();

    // Disable low priority global interrupts.
    //INTERRUPT_GlobalInterruptLowDisable();

    // Enable the Global Interrupts
    //INTERRUPT_GlobalInterruptEnable();

    // Disable the Global Interrupts
    //INTERRUPT_GlobalInterruptDisable();

    // Enable the Peripheral Interrupts
    //INTERRUPT_PeripheralInterruptEnable();

    // Disable the Peripheral Interrupts
    //INTERRUPT_PeripheralInterruptDisable();
    if( _card_insert() == 0 )
    {
	  printf("-- SD card detected OK \r\n");
    }
    else
    {
      printf("-- Please connect a SD card \r\n"     );
      while( _card_insert() != 0 );
      printf("-- SD card connection detected \r\n");
	  __delay_ms(10);
    }
    
	f_mount(&fs,"",0);	

    
	res = f_open( &fsrc , "Simple2.csv" , FA_CREATE_NEW | FA_WRITE | FA_OPEN_APPEND);		

    if ( res == FR_OK )
    { 
      /* Write buffer to file */
      res = f_write(&fsrc, textFileBuffer, sizeof(textFileBuffer), &br);     
 
      if(res == FR_OK){
      
        printf("Simple2.csv successfully created        %u\r\n",br);
        
      }else{
      
          printf("Simple2.csv successfully created with some Error        %u\r\n",res);
      
      
      }
    
      /*close file */
      f_close(&fsrc);      
    }
    else if ( res == FR_EXIST )
    {
	  printf("Demo.TXT created in the disk      \r\n");
    }
    f_close(&fsrc);
    SD_TotalSize();
    
    f_mount(0,"",0);

    while(1)
    {
        // Add your application code
    }
}
/**
 End of File
*/

¡Saludos!
 

Adjuntos

  • SDCard.X.zip
    4.8 MB · Visitas: 25
Atrás
Arriba