mbed-os storage access example.
Dependencies: SDBlockDevice_GR_PEACH USBHost_custom
This is a sample for using USB memory and SD card in mbed-os 5.4 or later version.
Import program
00001 #include "mbed.h" 00002 #include "FATFileSystem.h" 00003 #include "SDBlockDevice_GR_PEACH.h" 00004 #include "USBHostMSD.h" 00005 00006 int main() { 00007 int i = 0; 00008 int storage_type = 0; 00009 char storage_str[16]; 00010 00011 FATFileSystem fs("storage"); 00012 SDBlockDevice_GR_PEACH sd; 00013 USBHostMSD usb; 00014 00015 while(1) { 00016 // try to connect a storage device 00017 while (1) { 00018 if (sd.connect()) { 00019 storage_type = 0; // SD 00020 strcpy(storage_str, "SD card"); 00021 fs.mount(&sd); 00022 break; 00023 } 00024 if (usb.connect()) { 00025 storage_type = 1; // USB 00026 strcpy(storage_str, "USB memory"); 00027 fs.mount(&usb); 00028 break; 00029 } 00030 Thread::wait(500); 00031 } 00032 00033 // in a loop, append a file 00034 // if the device is disconnected, we try to connect it again 00035 while(1) { 00036 // append a file 00037 FILE * fp = fopen("/storage/test1.txt", "a"); 00038 00039 if (fp != NULL) { 00040 fprintf(fp, "Hello %s World: %d!\r\n", storage_str, i++); 00041 printf("Goodbye World!\r\n"); 00042 fclose(fp); 00043 } else { 00044 printf("FILE == NULL\r\n"); 00045 } 00046 Thread::wait(500); 00047 00048 // if device disconnected, try to connect again 00049 if (storage_type == 0) { 00050 if (!sd.connected()) break; 00051 } else { 00052 if (!usb.connected()) break; 00053 } 00054 } 00055 fs.unmount(); 00056 } 00057 }
Diff: main.cpp
- Revision:
- 1:c1b5260c1491
- Parent:
- 0:392df152119c
--- a/main.cpp Thu Mar 16 09:28:46 2017 +0000 +++ b/main.cpp Tue Mar 21 04:10:37 2017 +0000 @@ -5,8 +5,8 @@ int main() { int i = 0; - int strage_type = 0; - char strage_str[16]; + int storage_type = 0; + char storage_str[16]; FATFileSystem fs("storage"); SDBlockDevice_GR_PEACH sd; @@ -14,17 +14,16 @@ while(1) { // try to connect a storage device - fs.unmount(); while (1) { if (sd.connect()) { - strage_type = 0; // SD - strcpy(strage_str, "SD card"); + storage_type = 0; // SD + strcpy(storage_str, "SD card"); fs.mount(&sd); break; } if (usb.connect()) { - strage_type = 1; // USB - strcpy(strage_str, "USB memory"); + storage_type = 1; // USB + strcpy(storage_str, "USB memory"); fs.mount(&usb); break; } @@ -38,7 +37,7 @@ FILE * fp = fopen("/storage/test1.txt", "a"); if (fp != NULL) { - fprintf(fp, "Hello %s World: %d!\r\n", strage_str, i++); + fprintf(fp, "Hello %s World: %d!\r\n", storage_str, i++); printf("Goodbye World!\r\n"); fclose(fp); } else { @@ -47,11 +46,12 @@ Thread::wait(500); // if device disconnected, try to connect again - if (strage_type == 0) { + if (storage_type == 0) { if (!sd.connected()) break; } else { if (!usb.connected()) break; } } + fs.unmount(); } }