简体   繁体   English

我应该如何在 Mbed 中有效地写入 sd 卡?

[英]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.我一直在尝试使用 SD 卡将数据记录到我的 NUCLEO F746ZG。 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.它以前工作过一次或两次,但只有在我上传代码之前有SD卡时才能工作,并且当我按下重置按钮时不会重写到SD卡。 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?有可能是我刚刚损坏了 sd 卡,还是我的代码有问题?

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.格式化您的 SD 卡以重新开始,然后始终关闭代码中的文件。

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.因此,即使您编写代码,这些字节也只会存在于 RAM 中,直到达到某个阈值,或者通常它们会保留在 RAM 中,直到您关闭它。 Then it does the actual file write in one go.然后它将实际文件写入一个 go。 This saves time when the code runs.这样可以节省代码运行的时间。 Also, close might do some cleanup on the SD card FAT table此外,关闭可能会对 SD 卡 FAT 表进行一些清理

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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