#include <18F4550.h>
#device adc=10

#FUSES NOWDT                    //No Watch Dog Timer
#FUSES WDT128                   //Watch Dog Timer uses 1:128 Postscale
#FUSES XTPLL                    //Crystal/Resonator with PLL enabled
#FUSES NOPROTECT                //Code not protected from reading
#FUSES NOBROWNOUT               //No brownout reset
//#FUSES BORV20                   //Brownout reset at 2.0V
#FUSES PUT                      //Power Up Timer
#FUSES NOCPD                    //No EE protection
#FUSES STVREN                   //Stack full/underflow will cause reset
#FUSES NODEBUG                  //No Debug mode for ICD
#FUSES NOLVP                    //No low voltage prgming, B3(PIC16) or B5(PIC18) used for I/O
#FUSES NOWRT                    //Program memory not write protected
#FUSES NOWRTD                   //Data EEPROM not write protected
#FUSES IESO                     //Internal External Switch Over mode enabled
#FUSES FCMEN                    //Fail-safe clock monitor enabled
#FUSES NOPBADEN                 //PORTB pins are configured as digital I/O on RESET
#FUSES NOWRTC                   //configuration not registers write protected
#FUSES NOWRTB                   //Boot block not write protected
#FUSES NOEBTR                   //Memory not protected from table reads
#FUSES NOEBTRB                  //Boot block not protected from table reads
#FUSES NOCPB                    //No Boot Block code protection
#FUSES MCLR                     //Master Clear pin enabled
#FUSES LPT1OSC                  //Timer1 configured for low-power operation
#FUSES NOXINST                  //Extended set extension and Indexed Addressing mode disabled (Legacy mode)
#FUSES PLL1                     //No PLL PreScaler
#FUSES CPUDIV1                  //System Clock by 1
#FUSES USBDIV                   //USB clock source comes from PLL divide by 2
#FUSES VREGEN                   //USB voltage regulator enabled
#FUSES ICPRT                    //ICPRT enabled
////////////////////////////////////
////  FIN DE FUSES   ///////////////
////////////////////////////////////
#use delay(clock=48000000)
#use rs232(baud=9600,xmit=PIN_B2,rcv=PIN_B1,bits=8) 
#define MFRC522_CS PIN_B5               
#define MFRC522_SCK PIN_B1
#define MFRC522_SI  PIN_C7                          
#define MFRC522_SO  PIN_B0              
#define MFRC522_RST PIN_B4                                                  
#include<Lib_rc522.h>
////////////////////////////////////
//////   DECLARACION RC522    //////
////////////////////////////////////
#define CS  PIN_B2
#define SCK  PIN_B1
#define MOSI PIN_C7
#define MISO PIN_B0
#USE RS232(baud=19200, xmit=PIN_C1, rcv=PIN_C2)
#USE SPI(MASTER,BAUD=1000000,SAMPLE_RISE,MSB_FIRST,DI=MISO,DO=MOSI,CLK=SCK,BITS=8,STREAM=RFID)
#byte TRISA=0xF92
#byte TRISB=0xF93
#byte TRISC=0xF94
#byte TRISD=0xF95
#byte TRISE=0xF95
#byte PORTA=0xF80
#byte PORTB=0xF81
#byte PORTC=0xF82
#byte PORTD=0xF83
#byte PORTE=0xF84
#include <FAT16.c>
///////////////////////////////////
//////   FIN DECLARACION SD   /////
///////////////////////////////////
sd();

/////////   PRINCIPAL   //////////
  CHAR UID[6];
void main()
{ 
   output_high(pin_A0);
   UNSIGNED int TagType;    
   CHAR i;   
   MFRC522_Init (); //Inicia al Módulo
  WHILE (TRUE)
   {  
    output_low(pin_B5);
    output_high(pin_B2);
        
      if (MFRC522_isCard (&TagType))      
      { output_high(pin_A1);
                                       
         //Read ID 
         if (MFRC522_ReadCardSerial (&UID))             
         { output_high(pin_A2);  
            for (i = 0; i < 5; i++)
            {
            
            }
          sd();  
         }                                       
         MFRC522_Halt () ;
      }
   }
}
      /////////////////////////////////////////////////////////
      ////////    termina la funciones de rc522    ///////////
      ////////////////////////////////////////////////////////
      sd()
      {
         UINT8 Texto[150]="\nEjemplo1;\r\n";  //UINT8 es un unsigned char
               //output_high(pin_B5);                      /// APAGO RC522
      
   char NombreCorto[13];
   char NombreLargo[30]="Ingeniera Electronica";
   char NombreCorto1[13]="ARCHIVO.TXT";
   char NombreLargo1[30]="Archivo creado con Pic.txt";
   UINT16 UbicacionFolder=0;
   
   setup_adc_ports(NO_ANALOGS);
   setup_adc(ADC_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);
      
   TRISA=0b00000000;
   TRISB=0b00000001;
   TRISC=0b00000100;
   TRISD=0b00000000;
   TRISE=0b00000000; 
    output_low(pin_B2);
    output_high(pin_B5);
   
    InitHard_SDCard();  
   if(SDCard_init()==1)
      { 
      output_high(pin_C2);
      if(FAT_init()==1)
         { 
         output_high(pin_D0);
         printf("FAT inicializada correctamente\n\r");
         FAT_UpdateDateTime(4,8,16,9,40,15);
         strcpy(&NombreCorto[0],"/INGENI1");
         if(FAT_FindDirectory(&NombreCorto[0],DirectorioRaiz,&UbicacionFolder)==1)  // FAT_FindDirectory---> Devulve en UbicacionFolder la dirección de la carpeta INGEN para luego trabajar en ella
            {
            output_low(pin_A2);
            printf("Carpeta Encontrada, buscando archivo...\n\r");
            if(FAT_FindFile(&NombreCorto1[0],UbicacionFolder)==1)
               {
               printf("Existe archivo, se agregan datos\r\n");
               FAT_OpenAddFile(&NombreCorto1[0],UbicacionFolder,&UID[0]);
               }
            else //if 4
               {
               printf("No existe archivo, se crea\r\n");
               FAT_CreateFile(&NombreLargo1[0],&NombreCorto1[0],UbicacionFolder,&UID[0]);
               }
            }
         else //if 3   
            {
            output_high(pin_D1);
            printf("La carpeta ni el archivo existen! Creando...\n\r");
            strcpy(&NombreCorto[0],"INGENI1");
            UbicacionFolder=FAT_CreateDirectory(&NombreLargo[0],&NombreCorto[0],DirectorioRaiz);
            FAT_CreateFile(&NombreLargo1[0],&NombreCorto1[0],UbicacionFolder,&UID[0]);
            output_low(pin_D1);
            }
           output_low(pin_D0);  
         }
      else printf("Error, no se pudo Inicialzar FAT\n\r"); //if 2
      }
      output_low(pin_C2);
   
      
      
   }

