The program will open a file called test.txt in the root of the SD card, and will create one if it does not exist. It will then write "one two three four five" in the .txt file. It will then read the text and output the result. You will need a terminal application (I recommend PuTTy) in order to see the outputs. The current program overwrites anything that was previous on the SD card. To prevent this, change the "w" to "a" during the writing process. This changes the instruction from a 'write' to an 'append'.

Dependencies:   SDFileSystem mbed

Fork of SDFileSystem_HelloWorld by mbed official

Committer:
bentrevett
Date:
Thu Jul 24 12:55:11 2014 +0000
Revision:
1:2cf8f0893afd
Parent:
0:bdbd3d6fc5d5
Reading and Writing to SD Card;  ; Description:;  ; A small project made with mbed (mbed.org) on the FRDM-KL64 using the SD card capabilities.; The program will open a file called test.txt in the root of the SD card, and will create one if it does not exi

Who changed what in which revision?

UserRevisionLine numberNew contents of line
mbed_official 0:bdbd3d6fc5d5 1 #include "mbed.h"
mbed_official 0:bdbd3d6fc5d5 2 #include "SDFileSystem.h"
mbed_official 0:bdbd3d6fc5d5 3
bentrevett 1:2cf8f0893afd 4 SDFileSystem sd(PTE3, PTE1, PTE2, PTE4, "sd"); //mosi, miso, sclk, cs
bentrevett 1:2cf8f0893afd 5
bentrevett 1:2cf8f0893afd 6
bentrevett 1:2cf8f0893afd 7 #define charlimit 100
bentrevett 1:2cf8f0893afd 8 char words[charlimit];
bentrevett 1:2cf8f0893afd 9 int n=0,c;
bentrevett 1:2cf8f0893afd 10
mbed_official 0:bdbd3d6fc5d5 11 int main() {
bentrevett 1:2cf8f0893afd 12
bentrevett 1:2cf8f0893afd 13 //writing to SD card
bentrevett 1:2cf8f0893afd 14 printf("Opening SD card...\r\n");
bentrevett 1:2cf8f0893afd 15
bentrevett 1:2cf8f0893afd 16 FILE *fp = fopen("/sd/test.txt", "w");
bentrevett 1:2cf8f0893afd 17 if(fp == NULL) {
bentrevett 1:2cf8f0893afd 18 error("Could not open file for write!\r\n");
bentrevett 1:2cf8f0893afd 19 }
mbed_official 0:bdbd3d6fc5d5 20
bentrevett 1:2cf8f0893afd 21 printf("Writing to SD card...\r\n");
bentrevett 1:2cf8f0893afd 22 fprintf(fp, "one two three four five\r\n");
mbed_official 0:bdbd3d6fc5d5 23 fclose(fp);
bentrevett 1:2cf8f0893afd 24
bentrevett 1:2cf8f0893afd 25 //reading from SD card
bentrevett 1:2cf8f0893afd 26 FILE *fp1 =fopen("/sd/test.txt.", "r");
bentrevett 1:2cf8f0893afd 27 if(fp1==NULL){
bentrevett 1:2cf8f0893afd 28 error("Could not open file for read!\r\n");
bentrevett 1:2cf8f0893afd 29 }
bentrevett 1:2cf8f0893afd 30
bentrevett 1:2cf8f0893afd 31 printf("Reading from SD card...\r\n");
bentrevett 1:2cf8f0893afd 32
bentrevett 1:2cf8f0893afd 33 while((c=fgetc(fp1)) && c!=EOF){
bentrevett 1:2cf8f0893afd 34 words[n]=c;
bentrevett 1:2cf8f0893afd 35 n++;
bentrevett 1:2cf8f0893afd 36 }
bentrevett 1:2cf8f0893afd 37
bentrevett 1:2cf8f0893afd 38 printf("Read from SD card: %s",words);
bentrevett 1:2cf8f0893afd 39
bentrevett 1:2cf8f0893afd 40 fclose(fp1);
mbed_official 0:bdbd3d6fc5d5 41
mbed_official 0:bdbd3d6fc5d5 42 }