SD Card Help

Here’s a simple example showing how to use the VCS SD card save and load file API. This saves some information into a file called “test.h” on the SD card and then reads it back again.

#include "robot-config.h"

// storage for some information to save
uint8_t     myTestData[ 100 ];
uint8_t     myReadBuffer[ 1000 ];

int main() {
    // set the test data to something detectable
    for(int i=0;i<100;i++) {
        myTestData* = i * 2;
    }
    
    // write test data to SD Card
    int nWritten = Brain.SDcard.savefile( "test.h", myTestData, sizeof(myTestData) );

    // did that work ?
    if( nWritten > 0) {
        // display on screen how many bytes we wrote
        Brain.Screen.setCursor( 2, 2 );
        Brain.Screen.print( "We wrote %d bytes to the SD Card", nWritten );

        // now read it back into a different buffer
        int nRead = Brain.SDcard.loadfile( "test.h", myReadBuffer, sizeof(myReadBuffer) );

        // display on screen how many bytes we read
        Brain.Screen.setCursor( 3, 2 );
        Brain.Screen.print( "We read %d bytes from the SD Card", nRead );

        // and display some of the data
        Brain.Screen.setCursor( 6, 2 );
        for(int i=0;i<8;i++)
            Brain.Screen.print("%02X ", myReadBuffer*);
    }
    else {
        Brain.Screen.printAt( 10, 40, "Error writing to the SD Card" );        
    }
}

In addition to this, the standard C API can be used, code like this (just a snippet, will not compile)


    // Test C file API
    FILE *fp;
    printf("read VEX_Messages.h\r\n");
    fp = fopen( "VEX_Messages.h", "rb" );
    if( fp != NULL ) {
      fseek( fp, 0, SEEK_END );
      int len = ftell( fp );
      fseek( fp, 0, SEEK_SET );
      printf("that worked, size is %d\r\n", len);
      
      if( len > 0 && len < 128000 ) {
        char *buf = (char *)malloc( len );
        int nRead = fread( buf, 1, len, fp );
        printf("we read %d bytes\r\n", nRead );
        free(buf);
      }
      fclose(fp);
    }
    else {
      perror("could not open file");
      printf("\r");
    }

Also, under certain conditions C++ streams can be used but we have found some issues with VCS in this area so I would avoid that for now.**