Autor Tema: Comenzando con memorias SD/MMC. Librería a nivel hardware.  (Leído 158515 veces)

0 Usuarios y 1 Visitante están viendo este tema.

Desconectado JorgeS

  • PIC10
  • *
  • Mensajes: 5
Re: Comenzando con memorias SD/MMC. Librería a nivel hardware.
« Respuesta #180 en: 10 de Mayo de 2012, 13:11:25 »
Hola, estoy comenzando con esto de las memorias SD y tengo un problema:

Utilice la libreria 1.8 y  el ejemplo mas sencillo:
Código: [Seleccionar]
#include <18F4550.h>
#device adc=8
#fuses HSPLL,NOWDT,NOPROTECT,NOLVP,NODEBUG,USBDIV,PLL5,CPUDIV1,VREGEN
#use delay(clock=20000000)
#use rs232(baud=9600,parity=N,xmit=PIN_C6,rcv=PIN_C7,bits=8)
//#use spi(MASTER,BITS=8,MODE=3,FORCE_HW,stream=SDCard)


#include "FAT16.c"

UINT8 Texto[512]="Texto Creado con PIC....\r\n";

void main(){

   int1 Card_Work=0;
   
   char NombreCorto[13];
   char NombreLargo[50];
   UINT16 UbicacionFolder=0;
   
   setup_adc_ports(NO_ANALOGS|VSS_VDD);
   setup_adc(ADC_OFF);
   setup_psp(PSP_DISABLED);
   setup_wdt(WDT_OFF);
   setup_timer_0(RTCC_INTERNAL|RTCC_DIV_1);
   setup_timer_1(T1_DISABLED|T1_DIV_BY_1);
   setup_timer_2(T2_DISABLED,0,1);
   setup_timer_3(T3_DISABLED|T3_DIV_BY_1);
   setup_comparator(NC_NC_NC_NC);
   setup_vref(FALSE);
   
   InitHard_SDCard();
   delay_ms(1000); 
   

   while(1){
      if((SD_DETEC==0)&&(Card_Work==FALSE)){
         delay_ms(500);
         if(SD_DETEC==0){
            Card_work=1;
            SDCard_init();
            FAT_init();
            strcpy(&NombreCorto[0],"CARPET~1");
            strcpy(&NombreLargo[0],"Carpeta de PIC");
            UbicacionFolder=FAT_CreateDirectory(&NombreLargo[0],&NombreCorto[0],DirectorioRaiz);
            strcpy(&NombreCorto[0],"ARCHIV~1.txt");
            strcpy(&NombreLargo[0],"Archivo con PIC.txt");
            FAT_CreateFile(&NombreLargo[0],&NombreCorto[0],UbicacionFolder,&Texto[0]);
            FAT_OpenAddFile(&NombreCorto[0],UbicacionFolder,&Texto[0]);
         }
      }
         
         
      if((SD_DETEC==1)&&(Card_Work==TRUE)){
         Card_work=0;
      }
   }
 
}
   

Consegui una imagen de un ejemplo : imagen64.ima, y comence la simulacion comentando la parte de:

Código: [Seleccionar]
  /* #if defined(SDCARD_DEBUG)
      printf("\r\n--> Se envia CMD59 (Desactivación de CRC)\r\n");
   #endif
   // Se desactiva CRC.
   if(SDCard_send_command(CMD59,0,&Respuesta)==0){
      return(0);
   }
   if(Respuesta.R1.Val!=0){
      return(0);
   }*/
   

y en la simulación se tranca en se inicia sincronizacion, realizando algo de debugging encontre que el problema esta en, probe comentando el for, aumentando i<50,100 etc y no pasa de esa linea.
Código: [Seleccionar]
   for(i=0;i<20;i++) WriteMedia(0xFF);    // Para sincronización.
en WriteMedia(0xFF) que es la funcion:

Código: [Seleccionar]
void WriteMedia(UINT8 data_out){
   
  UINT8 TempVar; 
 
   #ifdef __18CXX
      TempVar = SSPBUF;           // Clears BF
      PIR1bits.SSPIF = 0;         // Clear interrupt flag
     
      SSPBUF = data_out;          // write byte to SSPBUF register
      while( !SSPSTATbits.BF );   // wait until bus cycle complete
   #endif
   #if defined(__PCH__)
      spi_write(data_out);
   #endif 
   #if defined (__PIC32MX__)
      TempVar = SPI1BUF; 
      SPI1BUF = data_out;              // Write to buffer for TX
      while( !SPI1STATbits.SPIRBF);    // Wait transfer complete
   #endif 
}

al parecer existe algun problema con el spi_write(0xFF), en anteriores versiones vi que utilizaron spi_xfer, y esas librerias antiguas si me funcionan.

Cual podría ser el problema?


PD: Tambien probé en Hardware, descomentando la parte del CRC, y no tengo respuesta. Utilizo el diagrama básico, con resistencias de 1.8k y 3.3k . En la SD tengo 3.15 V de voltaje (LM317) y con los divisores obtengo 3.13 V.

Esos voltajes son suficientes o debería llegar a los 3.3V?


Agradezco de antemano su ayuda!


Saludos


Jorge



Desconectado Suky

  • Moderadores
  • DsPIC33
  • *****
  • Mensajes: 6758
Re: Comenzando con memorias SD/MMC. Librería a nivel hardware.
« Respuesta #181 en: 10 de Mayo de 2012, 14:40:59 »
Sinceramente ya no utilizo CCS, o muy muy poco. Podes revisar que se ejecute OpenSPI(SPI_FOSC_64, MODE_11, SMPMID); y que se configuren los registros correctamente.


Saludos!
No contesto mensajes privados, las consultas en el foro

Desconectado JorgeS

  • PIC10
  • *
  • Mensajes: 5
Re: Comenzando con memorias SD/MMC. Librería a nivel hardware.
« Respuesta #182 en: 11 de Mayo de 2012, 10:23:16 »
Tenias razon!, en SDCardSPI.c tenia el llamado a:

Código: [Seleccionar]
   InitSPI(VELOCITY_SPI_LOW);
pero en HardwareSPI.c no estaba definida la opcion para PCH:

Código: [Seleccionar]
switch(Velocity){
      case VELOCITY_SPI_LOW:
         #ifdef __18CXX
         CloseSPI();
         OpenSPI(SPI_FOSC_64, MODE_11, SMPMID);
       
         #endif
       
         #if defined (__PIC32MX__)
         SPI1CON = 0x0000;
         SPI1BRG = 19;       // Clock = FCB/2*(19+1) = 1 MHz
         SPI1CON = 0x8120;   // ON, CKE=1; CKP=0, Sample Middle   
         #endif
      break;


Agregrandolo, ya pude pasar de sincronizacion :D, ahora voy a investigar por que obtengo este otro problema:




Saludos


Jorge

Desconectado JorgeS

  • PIC10
  • *
  • Mensajes: 5
Re: Comenzando con memorias SD/MMC. Librería a nivel hardware.
« Respuesta #183 en: 12 de Mayo de 2012, 15:31:29 »
Hola a todos, les cuento que ya tengo la simulacion funcionando, solo que ahora tengo problemas con el hardware....grabe el PIC descomentando la parte de:
Código: [Seleccionar]
  // Deshabilitado para simulación:
   #ifdef RS232_DEBUG
      printf("\r\n--> Se envia CMD59 (Desactivación de CRC)\r\n");
   #endif
   // Se desactiva CRC.
   if(SDCard_send_command(CMD59,0,Respuesta)==0){
      return(0);
   }else if(Respuesta!=0){
      return(0);
   }
 

Y no funciona, uso el hardware minimo con resistencias de 1.8k y 3.3k, alimento a la tarjeta SD con 3.24 V, y con el divisor resistivo tengo 3.20V. Probe aumentando un poco el voltaje de alimentacion de la SD a 3.4V, y no funciona.

Tengo una memoria Kingston de 2GB y una memoria SD que venia con un celular sony ericsson de 2 GB y ninguna funciona.

Les di formato con el programa: SDFormatter  con la opcion OverWrite, luego de intentar escribir algo, formatee con XP en 2 computadoras distintas y nada!!  :( :(


Esta es la imagen del WinHex de una de mis memorias:




Y esta de la segunda memoria, en el sector donde se realizo el overwrite con las y:






¿Alguna sugerencia?


Agradezco de antemano su ayuda



Saludos


Jorge

Desconectado Suky

  • Moderadores
  • DsPIC33
  • *****
  • Mensajes: 6758
Re: Comenzando con memorias SD/MMC. Librería a nivel hardware.
« Respuesta #184 en: 12 de Mayo de 2012, 15:59:06 »
Nada de nada? O sea, no inicializa? El debug que indica?
No contesto mensajes privados, las consultas en el foro

Desconectado JorgeS

  • PIC10
  • *
  • Mensajes: 5
Re: Comenzando con memorias SD/MMC. Librería a nivel hardware.
« Respuesta #185 en: 12 de Mayo de 2012, 16:15:23 »
Estoy realizando el Debug con unos LEDs, y al parecer llega al final del programa sin inconvenientes  :?


EDITADO:


Adjunto el programa y su simulacion, estoy usando una version anterior de fat16 la 1.3 por que no necesito buscar ni la compatibilidad con C18.

« Última modificación: 29 de Mayo de 2012, 21:39:54 por JorgeS »

Desconectado Suky

  • Moderadores
  • DsPIC33
  • *****
  • Mensajes: 6758
Re: Comenzando con memorias SD/MMC. Librería a nivel hardware.
« Respuesta #186 en: 12 de Mayo de 2012, 17:45:52 »
Recomiendo usar la 1.8 que trata de solucionar algunos bug. 1.3 totalmente obsoleta  ;-)


Saludos!
No contesto mensajes privados, las consultas en el foro

Desconectado JorgeS

  • PIC10
  • *
  • Mensajes: 5
Re: Comenzando con memorias SD/MMC. Librería a nivel hardware.
« Respuesta #187 en: 12 de Mayo de 2012, 21:42:32 »
Suky al implementar la version 1.8, tengo un ciclo infinito en fat_init()



supongo que se da en la parte de:

Código: [Seleccionar]
  if(SDCard_read_block(0,&BufferFAT[0])==0){
     
      return(0);
     
   }


Disculpa mi ignorancia, pero por mas que vea el codigo no entiendo donde podria estar el error en la parte de:

Código: [Seleccionar]
SDCard_read_block(UINT32 Address,UINT8 *Buffer){
   
   SDCARD_RESPUESTA Respuesta;
   UINT8 TokenTmp;
   UINT16 i;
   
   // Se envia comando para leer bloque de bytes.-
   #if defined(SDCARD_DEBUG)
      printf("\r\n--> Se envia CMD17 (Lectura de bloque)\r\n");
   #endif
   SDSelect();
   if(SDCard_send_command(CMD17,Address,&Respuesta)==0){
      return(0);
   }
   if(Respuesta.R1.Val!=0){
      return(0);
   } 
// Pasamos a esperar Token.
   i=0;
   do{
      TokenTmp=ReadMedia();
      i++;
   }while(TokenTmp==0xFF && i<SDCARD_TIMEOUT);// Mientras sea 0xFF.-
   if(i>=SDCARD_TIMEOUT){SDDeselect();return(0);}
   if((TokenTmp&0xE0)==0){ // Si se recibe 000xxxxx y no 0xFE.-
      SDDeselect();
      return(0);
   }
   #if defined(SDCARD_DEBUG)
   //   printf("Toquen recibido: 0x%X\r\n",TokenTmp);
   #endif
   // Todo ok, recibimos data.-
   for(i=0;i<BLOCK_SIZE;i++){
      *Buffer++=ReadMedia();
   }
   // Ignoramos CRC.-
   ReadMedia();
   ReadMedia();
   
   SDDeselect();
   #if defined(SDCARD_DEBUG)
   //   printf("Terminada la lectura\r\n");
   #endif
   
   return(1);   


No entiendo por que no funcionaria la simulación, por que en el foro de ucontrol vi, que para probar la libreria solo hay que copiar el código ejemplo, agregar librerias y compilar. De tantos intentos creí que la simulación era la que fallaba así que compile el ejemplo con la librería 1.8 lo probé en el hardware e igualmente no me escribe nada :( como puse en el post anterior.

De tan frustrado que estoy con esto del CCS, estoy pasandome al C18 espero tener mejor suerte xD.

¿Alguna idea de por que tengo ese ciclo infinito?


Saludos


Jorge

Desconectado churrinfunflais

  • PIC12
  • **
  • Mensajes: 68
Re: Comenzando con memorias SD/MMC. Librería a nivel hardware.
« Respuesta #188 en: 05 de Junio de 2012, 15:19:17 »
Hola!!!

Eh estado tratando de implementar una memoria SD en mis proyectos pero no lo logro, eh seguido el AN1045 y nada también la guia de Suky y no logro compilar también eh intentado el ejemplo que biene en el stack de microchip , sera que tengo algo mal??

ejemplo del Stack:
Código: [Seleccionar]
/******************************************************************************
 *
 *               Microchip Memory Disk Drive File System
 *
 ******************************************************************************
 * FileName:        Demonstration.c
 * Dependencies:    FSIO.h
 * Processor:       PIC18
 * Compiler:        C18
 * Company:         Microchip Technology, Inc.
 *
 * Software License Agreement
 *
 * The software supplied herewith by Microchip Technology Incorporated
 * (the �Company�) for its PICmicro� Microcontroller is intended and
 * supplied to you, the Company�s customer, for use solely and
 * exclusively on Microchip PICmicro Microcontroller products. The
 * software is owned by the Company and/or its supplier, and is
 * protected under applicable copyright laws. All rights are reserved.
 * Any use in violation of the foregoing restrictions may subject the
 * user to criminal sanctions under applicable laws, as well as to
 * civil liability for the breach of the terms and conditions of this
 * license.
 *
 * THIS SOFTWARE IS PROVIDED IN AN �AS IS� CONDITION. NO WARRANTIES,
 * WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED
 * TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. THE COMPANY SHALL NOT,
 * IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL OR
 * CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
 *
 *****************************************************************************/


/*****************************************************************************
        Note:  This file is included to give you a basic demonstration of how the
           functions in this library work.  Prototypes for these functions,
           along with more information about them, can be found in FSIO.h
 *****************************************************************************/

//DOM-IGNORE-BEGIN
/********************************************************************
 Change History:
  Rev            Description
  ----           -----------------------
  1.2.4 - 1.2.6  No Change
  1.2.6          Add support for the PIC18F46J50_PIM
  1.3.4          Added support for PIC18F8722 on PIC18 Explorer Board
 ********************************************************************/
//DOM-IGNORE-END


#include "FSIO.h"


#if defined(PIC18F87J50_PIM) // Configuration bits for PIC18F87J50 FS USB Plug-In Module board
#pragma config XINST    = OFF    // Extended instruction set
#pragma config STVREN   = ON      // Stack overflow reset
#pragma config PLLDIV   = 3         // (12 MHz crystal used on this board)
#pragma config WDTEN    = OFF      // Watch Dog Timer (WDT)
#pragma config CP0      = OFF      // Code protect
#pragma config CPUDIV   = OSC1      // OSC1 = divide by 1 mode
#pragma config IESO     = OFF      // Internal External (clock) Switchover
#pragma config FCMEN    = OFF      // Fail Safe Clock Monitor
#pragma config FOSC     = HSPLL     // Firmware must also set OSCTUNE<PLLEN> to start PLL!
#pragma config WDTPS    = 32768
//      #pragma config WAIT     = OFF      // Commented choices are
//      #pragma config BW       = 16      // only available on the
//      #pragma config MODE     = MM      // 80 pin devices in the
//      #pragma config EASHFT   = OFF      // family.
#pragma config MSSPMSK  = MSK5
//      #pragma config PMPMX    = DEFAULT
//      #pragma config ECCPMX   = DEFAULT
#pragma config CCP2MX   = DEFAULT   
#elif defined(PIC18F46J50_PIM)
#pragma config WDTEN = OFF          //WDT disabled (enabled by SWDTEN bit)
#pragma config PLLDIV = 3           //Divide by 3 (12 MHz oscillator input)
#pragma config STVREN = ON            //stack overflow/underflow reset enabled
#pragma config XINST = OFF          //Extended instruction set disabled
#pragma config CPUDIV = OSC1        //No CPU system clock divide
#pragma config CP0 = OFF            //Program memory is not code-protected
#pragma config OSC = HSPLL          //HS oscillator, PLL enabled, HSPLL used by USB
#pragma config T1DIG = ON           //Sec Osc clock source may be selected
#pragma config LPT1OSC = OFF        //high power Timer1 mode
#pragma config FCMEN = OFF          //Fail-Safe Clock Monitor disabled
#pragma config IESO = OFF           //Two-Speed Start-up disabled
#pragma config WDTPS = 32768        //1:32768
#pragma config DSWDTOSC = INTOSCREF //DSWDT uses INTOSC/INTRC as clock
#pragma config RTCOSC = T1OSCREF    //RTCC uses T1OSC/T1CKI as clock
#pragma config DSBOREN = OFF        //Zero-Power BOR disabled in Deep Sleep
#pragma config DSWDTEN = OFF        //Disabled
#pragma config DSWDTPS = 8192       //1:8,192 (8.5 seconds)
#pragma config IOL1WAY = OFF        //IOLOCK bit can be set and cleared
#pragma config MSSP7B_EN = MSK7     //7 Bit address masking
#pragma config WPFP = PAGE_1        //Write Protect Program Flash Page 0
#pragma config WPEND = PAGE_0       //Start protection at page 0
#pragma config WPCFG = OFF          //Write/Erase last page protect Disabled
#pragma config WPDIS = OFF          //WPFP[5:0], WPEND, and WPCFG bits ignored
#elif defined(__18F8722)
#pragma config OSC=HSPLL, FCMEN=OFF, IESO=OFF, PWRT=OFF, WDT=OFF, LVP=OFF, XINST=OFF
#else
#endif

char sendBuffer[22] = "This is test string 1";
char send2[2] = "2";
char receiveBuffer[50];

char dirname1[16] = ".\\ONE\\TWO\\THREE";
char dirname2[14] = "ONE\\TWO\\THREE";
char dirname3[14] = "FOUR\\FIVE\\SIX";
char dirname4[60] = "FOUR\\FIVE\\SEVEN\\..\\EIGHT\\..\\..\\NINE\\TEN\\..\\ELEVEN\\..\\TWELVE";
char dirname5[31] = "\\ONE\\TWO\\THREE\\FOUR\\FIVE\\EIGHT";
char dirname6[10] = "FOUR\\NINE";
char dirname7[2];

void main(void) {
    FSFILE * pointer;
    char path[30];
    char count = 30;
    char * pointer2;
    SearchRec rec;
    unsigned char attributes;
    unsigned char size = 0, i;

#if (defined(__18CXX) & !defined(PIC18F87J50_PIM)) || defined(__18F8722)
    ADCON1 |= 0x0F; // Default all pins to digital
#elif !defined(PIC18F87J50_PIM)
    AD1PCFG = 0xFFFF;
#endif
#if defined(PIC18F87J50_PIM)
    WDTCONbits.ADSHR = 1; // Select alternate SFR location to access ANCONx registers
    ANCON0 = 0xFF; // Default all pins to digital
    ANCON1 = 0xFF; // Default all pins to digital
    WDTCONbits.ADSHR = 0; // Select normal SFR locations
#endif
#if defined(PIC18F46J50_PIM)
    ANCON0 = 0xFF; // Default all pins to digital
    ANCON1 = 0xFF; // Default all pins to digital
#endif
    //********* Initialize Peripheral Pin Select (PPS) *************************
    //  This section only pertains to devices that have the PPS capabilities.
    //    When migrating code into an application, please verify that the PPS
    //    setting is correct for the port pins that are used in the application.
#if defined(PIC18F46J50_PIM)
    RPINR21 = 1; //SDI = RP1
    RPOR4 = 10; //RP4 = SCK
    RPOR2 = 9; //RP2 = SDO
    RPINR22 = 4; //SCK = RP4

    //enable a pull-up for the card detect, just in case the SD-Card isn't attached
    //  then lets have a pull-up to make sure we don't think it is there.
    INTCON2bits.RBPU = 0;

#endif
    while (!MDD_MediaDetect());

    // Initialize the library
    while (!FSInit());

#ifdef ALLOW_WRITES
    // Set the clock value
    // This will determine the create time for the file we're about to make
    // This will set the time and date to 3:05:26 PM on July 27, 2007.
    if (SetClockVars(2007, 7, 27, 15, 5, 26))
        while (1);

    // Create a file
    pointer = FSfopenpgm("FILE3.TXT", "w");
    if (pointer == NULL)
        while (1);

    // Write 21 1-byte objects from sendBuffer into the file
    if (FSfwrite((void *) sendBuffer, 1, 21, pointer) != 21)
        while (1);

    // FSftell returns the file's current position
    if (FSftell(pointer) != 21)
        while (1);

    // FSfseek sets the position one byte before the end
    // It can also set the position of a file forward from the
    // beginning or forward from the current position
    if (FSfseek(pointer, 1, SEEK_END))
        while (1);

    // Write a 2 at the end of the string
    if (FSfwrite((void*) send2, 1, 1, pointer) != 1)
        while (1);

    // Set the time again
    // When called before fclose, this will determine the last time
    // accessed and modified.  This time will be 4 seconds after the last one.
    if (SetClockVars(2007, 7, 27, 15, 5, 30))
        while (1);

    // Close the file
    if (FSfclose(pointer))
        while (1);

    // Set the clock again
    // This time is the last one possible with the FAT file system
    // 11:59:59 PM, December 31, 2106.
    if (SetClockVars(2107, 12, 31, 23, 59, 59))
        while (1);

    // Create a second file
    pointer = FSfopenpgm("FILE1.TXT", "w");
    if (pointer == NULL)
        while (1);

    // Write the string to it again
    if (FSfwrite((void *) sendBuffer, 1, 21, pointer) != 21)
        while (1);

    // Close the file
    if (FSfclose(pointer))
        while (1);
#endif

    // Open file 1 in read mode
    pointer = FSfopenpgm("FILE3.TXT", "r");
    if (pointer == NULL)
        while (1);

    if (FSrenamepgm("FILE2.TXT", pointer))
        while (1);

    // Read one four-byte object
    if (FSfread(receiveBuffer, 4, 1, pointer) != 1)
        while (1);

    // Check if this is the end of the file- it shouldn't be
    if (FSfeof(pointer))
        while (1);

    // Close the file
    if (FSfclose(pointer))
        while (1);

    // Make sure we read correctly
    if ((receiveBuffer[0] != 'T') ||
            (receiveBuffer[1] != 'h') ||
            (receiveBuffer[2] != 'i') ||
            (receiveBuffer[3] != 's')) {
        while (1);
    }

#ifdef ALLOW_DIRS
    // Create a small directory tree
    // Beginning the path string with a '.' will create the tree in
    // the current directory.  Beginning with a '..' would create the
    // tree in the previous directory.  Beginning with just a '\' would
    // create the tree in the root directory.  Beginning with a dir name
    // would also create the tree in the current directory
    if (FSmkdir(dirname1))
        while (1);

    // Change to directory THREE in our new tree
    if (FSchdir(dirname2))
        while (1);

    // Create another tree in directory THREE
    if (FSmkdir(dirname3))
        while (1);

    // Create a third file in directory THREE
    pointer = FSfopenpgm("FILE3.TXT", "w");
    if (pointer == NULL)
        while (1);

    // Get the name of the current working directory
    /* it should be "\ONE\TWO\THREE"       */
    pointer2 = FSgetcwd(path, count);
    if (pointer2 != path)
        while (1);

    // Simple string length calculation
    i = 0;
    while (*(path + i) != 0x00) {
        size++;
        i++;
    }
    // Write the name to FILE3.TXT
    if (FSfwrite((void *) path, size, 1, pointer) != 1)
        while (1);

    // Close the file
    if (FSfclose(pointer))
        while (1);

    // Create some more directories
    if (FSmkdir(dirname4))
        while (1);

    /*******************************************************************
            Now our tree looks like this

            \ -> ONE -> TWO -> THREE -> FOUR -> FIVE -> SIX
                                             -> SEVEN
                                             -> EIGHT
                                        NINE -> TEN
                                             -> ELEVEN
                                             -> TWELVE
     ********************************************************************/

    // This will delete only directory eight
    // If we tried to delete directory FIVE with this call, the FSrmdir
    // function would return -1, since FIVE is non-empty
    if (FSrmdir(dirname5, FALSE))
        while (1);

    // This will delete directory NINE and all three of its sub-directories
    if (FSrmdir(dirname6, TRUE))
        while (1);

    // You can't initialize an array in PIC18 to just a backslash
    // Initialize it manually
    dirname7[0] = '\\';
    dirname7[1] = 0;
    // Change directory to the root dir
    if (FSchdir(dirname7))
        while (1);

#endif

#ifdef ALLOW_FILESEARCH
    // Set attributes
    attributes = ATTR_ARCHIVE | ATTR_READ_ONLY | ATTR_HIDDEN;

    // Functions "FindFirstpgm" & "FindNext" can be used to find files
    // and directories with required attributes in the current working directory.

    // Find the first TXT file with any (or none) of those attributes that
    // has a name beginning with the letters "FILE"
    // These functions are more useful for finding out which files are
    // in your current working directory
    if (FindFirstpgm("FILE*.TXT", attributes, &rec))
        while (1);

    // Keep finding files until we get FILE2.TXT
    while (rec.filename[4] != '2') {
        if (FindNext(&rec))
            while (1);
    }

    // Delete file 2.
    // NOTE : "FSremove" function deletes specific file not directory.
    //        To delete directories use "FSrmdir" function
    if (FSremove(rec.filename))
        while (1);
#endif

    /*********************************************************************
            The final contents of our card should look like this:
            \ -> FILE1.TXT
          -> ONE       -> TWO -> THREE -> FILE3.TXT
                                       -> FOUR      -> FIVE -> SIX
                                                            -> SEVEN

     *********************************************************************/


    while (1);
}

Error que aparece:
Código: [Seleccionar]
CLEAN SUCCESSFUL (total time: 67ms)
make -f nbproject/Makefile-default.mk SUBPROJECTS= .build-conf
make[1]: Entering directory `C:/Microchip Solutions v2012-04-03/MDD File System-SD Card/PIC18F/SD.X'
make  -f nbproject/Makefile-default.mk dist/default/production/SD.X.production.hex
make[2]: Entering directory `C:/Microchip Solutions v2012-04-03/MDD File System-SD Card/PIC18F/SD.X'
"X:\Program Files (x86)\Microchip\mplabc18\v3.40\bin\mcc18.exe"  -p18F8722 -I"C:/Microchip Solutions v2012-04-03/Microchip/Include/MDD File System" -I"C:/Microchip Solutions v2012-04-03/Microchip/Include" -I"C:/Microchip Solutions v2012-04-03/MDD File System-SD Card/PIC18F" -I"C:/Microchip Solutions v2012-04-03/MDD File System-SD Card"  -I "X:\Program Files (x86)\Microchip\mplabc18\v3.40\bin"\\..\\h  -fo build/default/production/_ext/1472/Demonstration.o   ../Demonstration.c
"X:\Program Files (x86)\Microchip\mplabc18\v3.40\bin\mplink.exe"  "..\18f8722_g.lkr"  -p18f8722  -w    -z__MPLAB_BUILD=1  -u_CRUNTIME -l "X:\Program Files (x86)\Microchip\mplabc18\v3.40\bin"\\..\\lib  -o dist/default/production/SD.X.production.cof  build/default/production/_ext/1472/Demonstration.o   
MPLINK 4.40, Linker
Device Database Version 1.3
Copyright (c) 1998-2011 Microchip Technology Inc.
Error - could not find definition of symbol 'FSremove' in file './build/default/production/_ext/1472/Demonstration.o'.
Errors    : 1

make[2]: Leaving directory `C:/Microchip Solutions v2012-04-03/MDD File System-SD Card/PIC18F/SD.X'
make[1]: Leaving directory `C:/Microchip Solutions v2012-04-03/MDD File System-SD Card/PIC18F/SD.X'
make[2]: *** [dist/default/production/SD.X.production.hex] Error 1
make[1]: *** [.build-conf] Error 2
make: *** [.build-impl] Error 2

BUILD FAILED (exit value 2, total time: 901ms)

Pareciese que no jala las funciones de la libreria "FSIO.h", que piensan??

Desconectado dejuninmza

  • PIC10
  • *
  • Mensajes: 11
Re: Comenzando con memorias SD/MMC. Librería a nivel hardware.
« Respuesta #189 en: 11 de Junio de 2012, 11:20:27 »
hola como estan?les comento que estoy en la implementación de un datalogger con el pic18f4550 y estoy usando la librerias de Suky FAT 1.8..la cuestión que hace unos meses estoy de cabeza con esto..ya logro crear y guardar datos en un archivo en la memoria sd...el problema surge debido a que después de almacenar muchos datos se vuelve lento añadir un dato en el archivo..por ejemplo si se guardan datos cada 1 segundo hay varias veces que el registro se hace cada 2 segundos..esto no pasa con la memoria vacía así que creo que la causa puede ser la búsqueda de un clúster libre en la memoria..además cdo el archivo es muy grande(100MB) también tengo problemas al guardar cada 1 min..la pregunta es si es posible solucionar este problema?..he visto como posible solución la de tener en una variable global el ultimo cluster utilizado pero no se bien como implementarlo..Hay alguna solución alternativa a esta ultima??..
Muchas gracias saludos

Desconectado churrinfunflais

  • PIC12
  • **
  • Mensajes: 68
Re: Comenzando con memorias SD/MMC. Librería a nivel hardware.
« Respuesta #190 en: 12 de Junio de 2012, 16:05:19 »
Aquí les dejo el proyecto en el que estoy trabajando.

Cambie al compilador CX8 para ver si había alguna diferencia pero sigo sin lograr compilar... Saludos

Código: [Seleccionar]
CLEAN SUCCESSFUL (total time: 117ms)
make -f nbproject/Makefile-default.mk SUBPROJECTS= .build-conf
make[1]: Entering directory `C:/Microchip Solutions v2012-04-03/MDD File System-SD Card/PIC18F/SD_Demo.X'
make  -f nbproject/Makefile-default.mk dist/default/production/SD_Demo.X.production.hex
make[2]: Entering directory `C:/Microchip Solutions v2012-04-03/MDD File System-SD Card/PIC18F/SD_Demo.X'
"C:\Program Files (x86)\Microchip\xc8\v1.00\bin\xc8.exe" --pass1  --chip=18F8722 -Q -G --asmlist  --double=24 --float=24 --emi=wordwrite --opt=all,+asm,-asmfile,+speed,-space,-debug,9 --addrqual=ignore --mode=pro -N31 --warn=0 --summary=default,-psect,-class,+mem,-hex,-file --runtime=default,+clear,+init,-keep,-no_startup,+osccal,-resetbits,-download,-stackcall,+config,+clib,+plib "--errformat=%%f:%%l: error: %%s" "--warnformat=%%f:%%l: warning: %%s" "--msgformat=%%f:%%l: advisory: %%s"  -obuild/default/production/main.p1  main.c
"C:\Program Files (x86)\Microchip\xc8\v1.00\bin\xc8.exe"  --chip=18F8722 -G --asmlist -mdist/default/production/SD_Demo.X.production.map  --double=24 --float=24 --emi=wordwrite --opt=all,+asm,-asmfile,+speed,-space,-debug,9 --addrqual=ignore --mode=pro -N31 --warn=0 --summary=default,-psect,-class,+mem,-hex,-file --runtime=default,+clear,+init,-keep,-no_startup,+osccal,-resetbits,-download,-stackcall,+config,+clib,+plib "--errformat=%%f:%%l: error: %%s" "--warnformat=%%f:%%l: warning: %%s" "--msgformat=%%f:%%l: advisory: %%s"   -odist/default/production/SD_Demo.X.production.cof  build/default/production/main.p1     
Microchip MPLAB XC8 C Compiler (Free Mode)  V1.00
Copyright (C) 2012 Microchip Technology Inc.
(1273) Omniscient Code Generation not available in Free mode (warning)
:: advisory: Employing 18F8722 errata work-arounds:
:: advisory:  * Corrupted fast interrupt shadow registers
main.c:167: warning: "RAM" is positioned at address 0x0 and has had its address taken; pointer comparisons may be invalid
:0: error: undefined symbols:
        _FSgetcwd(dist/default/production\SD_Demo.X.production.obj) _FSfclose(dist/default/production\SD_Demo.X.production.obj) _FSfwrite(dist/default/production\SD_Demo.X.production.obj) _FSremove(dist/default/production\SD_Demo.X.production.obj) _FindNext(dist/default/production\SD_Demo.X.production.obj) _FSrenamepgm(dist/default/production\SD_Demo.X.production.obj) _FSfeof(dist/default/production\SD_Demo.X.production.obj) _FSInit(dist/default/production\SD_Demo.X.production.obj) _FSfread(dist/default/production\SD_Demo.X.production.obj) _FSfseek(dist/default/production\SD_Demo.X.production.obj) _FSftell(dist/default/production\SD_Demo.X.production.obj) _FSchdir(dist/default/production\SD_Demo.X.production.obj) _FSmkdir(dist/default/production\SD_Demo.X.production.obj) _FSrmdir(dist/default/production\SD_Demo.X.production.obj) _FSfopenpgm(dist/default/production\SD_Demo.X.production.obj) _FindFirstpgm(dist/default/production\SD_Demo.X.production.obj) _MDD_SDSPI_MediaDetect(dist/default/production\SD_Demo.X.production.obj) _SetClockVars(dist/default/production\SD_Demo.X.production.obj)
make[2]: Leaving directory `C:/Microchip Solutions v2012-04-03/MDD File System-SD Card/PIC18F/SD_Demo.X'
make[1]: Leaving directory `C:/Microchip Solutions v2012-04-03/MDD File System-SD Card/PIC18F/SD_Demo.X'
(908) exit status = 1
make[2]: *** [dist/default/production/SD_Demo.X.production.hex] Error 1
make[1]: *** [.build-conf] Error 2
make: *** [.build-impl] Error 2

BUILD FAILED (exit value 2, total time: 2s)

Desconectado churrinfunflais

  • PIC12
  • **
  • Mensajes: 68
Re: Comenzando con memorias SD/MMC. Librería a nivel hardware.
« Respuesta #191 en: 13 de Junio de 2012, 12:54:25 »
Al fin,, Logre compilar el proyecto ahora lo estoy tratando de simular en el proteus pero nunca eh usado el simulador de SD, que es lo que debo saber para poder utilizarlo de forma correcta, al parecer me pide una imagen, esto que significa, también no se si mi circuito es correcto, según yo realice las conexiones que indica el archivo HardwareProfile.h pero no estoy seguro de estar haciéndolo bien... un poco de ayuda please..

Código: [Seleccionar]
#elif defined(__18F8722)

        #define USE_PIC18
        #define USE_SD_INTERFACE_WITH_SPI

        #define INPUT_PIN           1
        #define OUTPUT_PIN          0

        // Chip Select Signal
        #define SD_CS               PORTBbits.RB3
        #define SD_CS_TRIS          TRISBbits.TRISB3

        // Card detect signal
        #define SD_CD               PORTBbits.RB4
        #define SD_CD_TRIS          TRISBbits.TRISB4

        // Write protect signal
        #define SD_WE               PORTAbits.RA4
        #define SD_WE_TRIS          TRISAbits.TRISA4

        // Registers for the SPI module you want to use
        #define SPICON1             SSP1CON1
        #define SPISTAT             SSP1STAT
        #define SPIBUF              SSP1BUF
        #define SPISTAT_RBF         SSP1STATbits.BF
        #define SPICON1bits         SSP1CON1bits
        #define SPISTATbits         SSP1STATbits

        #define SPI_INTERRUPT_FLAG  PIR1bits.SSPIF

        // Defines for the HPC Explorer board
        #define SPICLOCK            TRISCbits.TRISC3
        #define SPIIN               TRISCbits.TRISC4
        #define SPIOUT              TRISCbits.TRISC5

        // Latch pins for SCK/SDI/SDO lines
        #define SPICLOCKLAT         LATCbits.LATC3
        #define SPIINLAT            LATCbits.LATC4
        #define SPIOUTLAT           LATCbits.LATC5

        // Port pins for SCK/SDI/SDO lines
        #define SPICLOCKPORT        PORTCbits.RC3
        #define SPIINPORT           PORTCbits.RC4
        #define SPIOUTPORT          PORTCbits.RC5

        #define SPIENABLE           SSPCON1bits.SSPEN

#define SPI_INTERRUPT_FLAG_ASM  PIR1, 3

        // Will generate an error if the clock speed is too low to interface to the card
        #if (GetSystemClock() < 400000)
            #error System clock speed must exceed 400 kHz
        #endif

Saludos...
Diagrama
« Última modificación: 13 de Junio de 2012, 13:00:41 por churrinfunflais »

Desconectado churrinfunflais

  • PIC12
  • **
  • Mensajes: 68
Re: Comenzando con memorias SD/MMC. Librería a nivel hardware.
« Respuesta #192 en: 13 de Junio de 2012, 14:20:23 »
Como puedo simular la inserción de la tarjeta en proteus?? alparecer esto es requerido para que el codigo avance , se lo contrario se queda esperando esta señal.

Código: [Seleccionar]
   while (!MDD_MediaDetect());

// Initialize the library
while (!FSInit());

Este codigo esta basado en el stack de microchip para almacenamiento masivo e implementado en "PIC18 Ecplorer Board" + "PICtail™ Daughter Board for SD™ and MMC Cards", los pines que utiliza son:

SCK   O   RC3/RB1   SPI Clock Out
SDI   I   RC4/RB0   SPI Data In
SDO   O   RC5/RC7   SPI Data Out
CD   I   RB4   Physical Card Insertion Detect Signal
WD   I   RA4   Physical Write-Protect Switch Status Signal
CS   O   RB3   Low Asserting SPI Chip Select
« Última modificación: 13 de Junio de 2012, 14:50:59 por churrinfunflais »

Desconectado mosesito

  • PIC10
  • *
  • Mensajes: 5
Re: Comenzando con memorias SD/MMC. Librería a nivel hardware.
« Respuesta #193 en: 01 de Septiembre de 2012, 04:29:45 »
Las SDHC soportan SPI ? Me parece que no, como máximo siempre se trabajó con memorias hasta 2Gb

hola amigo donde puedo bajar la libreria fat16 1.8  y tambien las mosificaciones de low speed y high speed producen error

donde agrego esas funciones saludos

Saludos!

Desconectado Mat_DM2012

  • PIC10
  • *
  • Mensajes: 3
Re: Comenzando con memorias SD/MMC. Librería a nivel hardware.
« Respuesta #194 en: 22 de Octubre de 2012, 19:45:48 »
Hola colegas... como les vá? no se si será el sobforo adecuado, pero estuve buscando ya hace varios dias y no encuentro aún nada. Lo que quiero es escribir y leer una tarjeta sd, el tema es que no manejo el "C" ni el "asembler", solo manejo y algo el Basic.
Quisiera que alguien me explique simplficadamente como hacer paa leer y escribir. Solo eso.

Espero que no les cause molestias...

Saludos y espero su ayuda con ansias...

nos vemos


 

anything