简体   繁体   中英

How to create a dynamic filename for an SD card on Arduino

I'd like to log my data on my Arduino one file at a time. I'd like the filename to be a combination of the number of milliseconds that have passed + some ID. For example, GPS data would be millis()+"GPS".

I tried the following code, but it doesn't like the fact that I am using a String . I could use a char array, but the length would always be dynamic. Is there a way to do this with at string somehow?

static void writeToSD()
{
    String logEntry = " GPS: ";
    logEntry += GPSString;
    String filename = String(millis());
    filename += "GPS";
    Serial.println(logEntry);
    Serial.println(filename);

    File dataFile = SD.open(filename, FILE_WRITE);

    // If the file is available, write to it:
    if (dataFile) {
        dataFile.println(logEntry);
        dataFile.close();
        Serial.println("Closed");
    }
    // If the file isn't open, pop up an error:
    else {
        Serial.println("error opening file");
    }
}

You could try the following

char fileNameCharArray[filename.length()];
filename.toCharArray(fileNameCharArray, filename.length())
File dataFile = SD.open(fileNameCharArray, FILE_WRITE);
sprintf (filename, "%ld-GPS", millis());

请注意,不推荐在Arduino上使用String, 因为有充分记录的内存泄漏/碎片问题

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