Reading an SD card file

My new mbed workshop breakout card arrived from Cool Components so I put my Battery Charger project aside (waiting for a transformer, anyway) to try out the SD card socket, using the program, later modified as below, from "Cookbook » SD Card File System", thank you for providing that. The first card I bought was an ambitious 4Gb but that gave no joy. My local computer shop man told me they are completely different from the 2Gb card, so I bought one of those and had success at last, in spite of it being FAT32. As I could not find anything about reading file content from the card, I set out to try that, and, as it worked, I thought I would post it here. Note that I edited the comments after I copied it from the compiler, hope this doesn't cause any problem:

&lt;<code>&gt; example writing to SD card, sford amended Harry Weston 060111 to read card as well output to Tera Term screen

  1. include "mbed.h"
  2. include "SDFileSystem.h"

SDFileSystem sd(p5, p6, p7, p8, "sd"); the pinout on the mbed Cool Components workshop board

  1. define MAXLINE 100 char myline [MAXLINE]; int i, inch ;

int main() { printf("\n\r= = = = = = = = = ="); printf("\n\rHello World!\n\r");

mkdir("/sd/mydir", 0777); Test that previous run had created permanent folder

/* FILE *fp = fopen("/sd/mydir/sdtest.txt", "w"); Commenting out, in a later run, from here .. if(fp == NULL) { | error("Could not open file for write\n"); | } | fprintf(fp, "Hello from SD Card World!"); | fclose(fp); | | printf("Created file\n\r"); .. to here shows file really is permanent .. .. since it still reads correctly.

  • / FILE *fp1 = fopen("/sd/mydir/sdtest.txt", "r"); if(fp1 == NULL) { error("Could not open file for read\n"); } printf("Opened file for read\n\r");

fscanf(fp1,"%s",&amp;myline); just reads the first word 'Hello'

i= 0; while ((inch = fgetc (fp1)) &amp;&amp; inch != EOF) { avoids an extra space at end of string for EOF myline[i++] = inch; }

printf("\n\rRead from SD card file: \"%s\"",myline);

fclose(fp1);

Trying to get Tera Term cursor to return at end to left margin on new line printf("\n\rGoodbye World!\n\r"); /* \n\r at end of format doesn't work ..

  • .. it just leaves the cursor under the end of this line */ printf("\n\r"); /* this doesn't either unless in format above as well ..
  • .. but now gives two line feeds at the end */ } &lt;</code>&gt;

Output as seen on Tera Term screen: &lt;<code>&gt;

= = = = = = = =

Hello World! Created file Opened file for read

Read from SD card file: "Hello from SD Card World!" Goodbye World!

(Tera Term cursor at the end)

&lt;</code>&gt;


Please log in to post comments.