#include "FAT32.h"

/*
This example opens or creates a "test.txt" file on the SD card, and appends
some text to the end of it.
The PortC.2 LED is used to indicate success/failure, with the following codes:
LED on - Success
1 Blink - Card not inserted
2 Blinks - Initialisation error
4 Blinks - File opening/creation error

The SD card needs to be formatted as FAT16. A tutorial on formatting
SDHC cards as FAT16 is available at www.dizzy.co.za/sdhc_fat16.asp
*/

//<MMC>
sbit MMC_Chip_Select at LATB7_bit;
sbit MMC_Chip_Select_Direction at TRISB7_bit;
sbit MMC_CD at RB1_bit; //Card-detect
sbit MMC_CD_Dir at TRISB1_bit;
//</MMC>

sbit LED at LATC2_bit;

char init_result;
short filehandle;

void Blink(char times) {
  char ctr;
  for (ctr=1;ctr<=times;ctr++) {
    LED = 1;
    delay_ms(500);
    LED = 0;
    delay_ms(500);
  }
}

void main() {
  OSCCON = 0b01110000;          //8MHz
  PLLEn_bit = 1;                //Enable PLL (now 48MHz)
  TRISC2_bit = 0;               //Make PortC.2 an output
  LED = 0;                      //Switch the LED off
  PCFG10_bit = 1;               //Make PortB.1 digital (not analogue)
  RBPU_bit = 0;                 //Enable weak pull-ups on PortB
  MMC_CD_dir = 1;               //Make MMC_CD (PortB.1) an input

  //Check if the SD card is inserted
  if (MMC_CD == 0) {
    //Initialise SPI at relatively low speed
    SPI1_Init_Advanced(_SPI_MASTER_OSC_DIV64, _SPI_DATA_SAMPLE_MIDDLE, _SPI_CLK_IDLE_LOW, _SPI_LOW_2_HIGH);
    //Initialise communication with the SD card
    init_result = FAT32_Init();
    if (init_result == 0) {
      //Reinitialise SPI at higher speed
      SPI1_Init_Advanced(_SPI_MASTER_OSC_DIV4, _SPI_DATA_SAMPLE_MIDDLE, _SPI_CLK_IDLE_LOW, _SPI_LOW_2_HIGH);
      //Find/create a file
      filehandle = FAT32_Open("test.txt", FILE_APPEND);
      if (filehandle != -1) {
        //Write to the file
        FAT32_Write(filehandle, "www.dizzy.co.za" "\x0D" "\x0A", 17);
        //Close the file
        FAT32_Close(filehandle);
        //Switch on the LED to indicate success
        LED = 1;
      } else {
        Blink(4); //File opening/creation error
      }
    } else {
      Blink(2); //Initialisation error
    }
  } else {
    Blink(1); //Card not inserted
  }
}