Arduino SD卡基于RTC生成文件名无法保存问题求助
Hey there! Let’s tackle that filename issue with your RTC-integrated data logging system. I’ve run into similar snags when working with SD cards and RTC modules, so let’s break this down step by step.
First, let’s recap what’s going on: your system worked fine when using integer-named .txt files, but now that you’re trying to generate filenames like Data_'DATE&TIME'.txt with an RTC module, the output is wrong and no files are showing up on the SD card. Let’s dig into the most likely culprits and fixes.
1. First: Verify Your RTC Is Giving Valid Time Data
The biggest red flag here is that if your RTC isn’t outputting correct date/time values, your filename will be garbage (or empty), and the SD card won’t create a file with an invalid name.
Add some debug prints to check what your RTC is returning:
// Inside your newFileName function or setup, print raw RTC values DateTime now = rtc.now(); // Adjust this to match your RTC library's syntax Serial.print("Year: "); Serial.println(now.year()); Serial.print("Month: "); Serial.println(now.month()); Serial.print("Day: "); Serial.println(now.day()); Serial.print("Hour: "); Serial.println(now.hour());
If any of these values are 0, garbage numbers, or out of range (like month 13), your RTC isn’t initialized properly. Double-check your RTC wiring, library setup, and whether you’ve set the time on the module (many RTCs lose time when unpowered!).
2. Fix Your Filename Format & Legality
SD cards use FAT32 (usually), which has strict filename rules:
- No illegal characters:
/ \ : * ? " < > |are all forbidden - While single quotes (
') are technically allowed, they’re unnecessary and can cause unexpected issues with string parsing - Consistent formatting helps avoid bugs (e.g., single-digit months/days should be padded with a 0, like
09instead of9)
Instead of building the filename with string concatenation (which can be flaky in Arduino), use sprintf to format it cleanly. Here’s a revised newFileName function:
String newFileName() { DateTime now = rtc.now(); // Match your RTC library's method to get current time char fileNameBuffer[30]; // Buffer big enough for our full filename // Format: Data_YYYYMMDD_HHMMSS.txt (no weird quotes, consistent padding) sprintf(fileNameBuffer, "Data_%04d%02d%02d_%02d%02d%02d.txt", now.year(), now.month(), now.day(), now.hour(), now.minute(), now.second()); return String(fileNameBuffer); }
This ensures every time component is properly padded (e.g., 5 minutes becomes 05) and avoids any messy string concatenation errors.
3. Check If The SD Card Is Actually Opening The File
Even if your filename is correct, you need to confirm that SD.open() is succeeding. Add debug checks here to catch errors:
String logFileName = newFileName(); Serial.print("Attempting to create file: "); Serial.println(logFileName); File dataFile = SD.open(logFileName, FILE_WRITE); if (dataFile) { // Write your data here dataFile.println("Test log entry"); dataFile.close(); Serial.println("File created & data saved successfully!"); } else { Serial.println("ERROR: Could not open file for writing!"); }
If you see the error message, it could mean:
- Your filename still has invalid characters
- The SD card is corrupted or not initialized properly (double-check your CS pin and wiring!)
- You’re out of space on the SD card
4. Review Your Previous Attempts
Looking at your commented-out solutions, if you were using String concatenation (like String fileName = "Data_" + date + "&" + time + ".txt";), this can cause issues if date or time are not properly formatted strings, or if the RTC returns empty values. The sprintf method avoids these pitfalls by forcing a consistent format.
Example Working Code Snippet
Here’s a condensed version of a working setup using RTClib and SD library:
#include <SD.h> #include <RTClib.h> RTC_DS3231 rtc; // Adjust to your RTC module (e.g., RTC_DS1307) void setup() { Serial.begin(9600); // Initialize SD card (adjust CS pin to match your hardware) if (!SD.begin(10)) { Serial.println("SD card init failed!"); while (1); // Halt if SD card isn't detected } // Initialize RTC if (!rtc.begin()) { Serial.println("RTC not found!"); while (1); } // Uncomment below to set RTC time (run once, then comment out) // rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); } String newFileName() { DateTime now = rtc.now(); char fileName[30]; sprintf(fileName, "Data_%04d%02d%02d_%02d%02d%02d.txt", now.year(), now.month(), now.day(), now.hour(), now.minute(), now.second()); return String(fileName); } void loop() { String fileName = newFileName(); File logFile = SD.open(fileName, FILE_WRITE); if (logFile) { logFile.println(millis()); // Write current millis as test data logFile.close(); Serial.print("Saved to file: "); Serial.println(fileName); } else { Serial.println("Failed to open file!"); } delay(5000); // Test every 5 seconds }
Final Notes
- Always test your filename output via Serial before trying to write to the SD card—this lets you catch formatting errors early
- Make sure your RTC module has a backup battery (if applicable) so it retains time when power is off
- Format your SD card as FAT32 (not exFAT or NTFS) if you haven’t already
内容的提问来源于stack exchange,提问作者Bert-Jan

