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 }
main.cpp
- Committer:
- dkato
- Date:
- 2017-03-23
- Revision:
- 2:30f86ef60767
- Parent:
- 1:c1b5260c1491
File content as of revision 2:30f86ef60767:
#include "mbed.h"
#include "FATFileSystem.h"
#include "SDBlockDevice_GR_PEACH.h"
#include "USBHostMSD.h"
int main() {
int i = 0;
int storage_type = 0;
char storage_str[16];
FATFileSystem fs("storage");
SDBlockDevice_GR_PEACH sd;
USBHostMSD usb;
while(1) {
// try to connect a storage device
while (1) {
if (sd.connect()) {
storage_type = 0; // SD
strcpy(storage_str, "SD card");
fs.mount(&sd);
break;
}
if (usb.connect()) {
storage_type = 1; // USB
strcpy(storage_str, "USB memory");
fs.mount(&usb);
break;
}
Thread::wait(500);
}
// in a loop, append a file
// if the device is disconnected, we try to connect it again
while(1) {
// append a file
FILE * fp = fopen("/storage/test1.txt", "a");
if (fp != NULL) {
fprintf(fp, "Hello %s World: %d!\r\n", storage_str, i++);
printf("Goodbye World!\r\n");
fclose(fp);
} else {
printf("FILE == NULL\r\n");
}
Thread::wait(500);
// if device disconnected, try to connect again
if (storage_type == 0) {
if (!sd.connected()) break;
} else {
if (!usb.connected()) break;
}
}
fs.unmount();
}
}