# Send a file to an SD card over SPI

I am using a PIC18F4620 and an XC8 compiler. I am trying to create a file and send it to the SD card. I am using the MDD library from the MLA Legacy. My main is:

FSFILE * file;
char sendBuffer[22] = "This is test string 1";

//**************************************************
// main function
//**************************************************
int main()
{
initIO();
PORTBbits.RB0 = 0;
while(1)
{
// Initialise SPI and SD-card
;

MDD_SDSPI_InitIO();

MDD_SDSPI_MediaInitialize();

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

#ifdef ALLOW_WRITES

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

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

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

#endif

MDD_SDSPI_SectorWrite(TAG_SECTOR_START, file, FALSE);

//    Delay10KTCYx(100000000);

PORTBbits.RB0 = 1;         //LED
}
return (0);
}


Does the code look OK? I am not sure about the MDD_SDSPI_SectorWrite function, and I don't know how to find the address of the sector in which I want to write the file. I know the error handling is bad. I will change it eventually.

• Why are you trying to bypass the filesystem write functions by calling SectorWrite directly? – brhans Jul 1 '15 at 15:52
• @brhans Should I call BYTE MDD_SDSPI_AsyncWriteTasks(ASYNC_IO* info); instead? – user2344158 Jul 1 '15 at 17:29
• I would expect that you should just use FSfwrite – brhans Jul 1 '15 at 17:48
• @brhans I think I have misunderstood the way the file system works. The file that created after calling the FSfopenpgm function is located in RAM on the PIC. How can that file be moved in the SD card instead. Correct me if I am wrong – user2344158 Jul 1 '15 at 17:55