简体   繁体   中英

how should i write to sd card effectively in Mbed?

I have been trying to record data to my NUCLEO F746ZG by using an sd card. This is my code:

#include "mbed.h"
#include "SDFileSystem.h"
//#include "Hx711.h"
#include <string>
//#include "ep29.h"
//#include "wsdef.h"
//#include "image.h"
//#include <vector>

PinName mosi = PE_6;
PinName miso = PE_5;
PinName sclk = PE_2;
PinName cs = PE_4;
PinName cd = PE_3;

SDFileSystem sd(mosi, miso, sclk, cs, "sd"); // the pinout on the mbed Cool Components workshop board
Serial pc(SERIAL_TX, SERIAL_RX);

int main(void) {
        pc.baud(9600);
        pc.printf("starting\r\n");
        FILE *fp = fopen("/sd/sdtest.txt", "w");
        if(fp == NULL) {
            pc.printf("Could not open file for write\n");
        }
        fprintf(fp,"starting to read from strain gauge:128G, 32G \r\n");
        fprintf(fp,"\r\n");
        pc.printf("worked!\r\n");
}

It had worked once or twice before, but would only work when I had the sd card in prior uploading the code, and would not rewrite to the sd card when I pressed the reset button. However, It doesn't seem to work at all anymore.

Is it likely that I just damamged to sd card, or is there something wrong in my code?

Cheers,

Ali

Kentaro had the right answer in the comment. Format your SD card to start over, then always close the file in your code.

Background: File operations are usually buffered. So even though you write in code, those bytes just live in RAM until some threshold is reached, or typically, they stay in RAM until you close it. Then it does the actual file write in one go. This saves time when the code runs. Also, close might do some cleanup on the SD card FAT table

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM