A. File is not closed after writing, risking data loss
B. Serial.println() cannot be used with SD cards
C. FILE_WRITE is not a valid mode for SD.open()
D. SD.begin() should be called after opening the file
Solution
Step 1: Check SD initialization
SD.begin() is correctly called before opening the file.
Step 2: Identify missing file.close()
The file is opened and written to, but not closed, which can cause data not to be saved properly.
Final Answer:
File is not closed after writing, risking data loss -> Option A
Quick Check:
Always close file after writing to save data [OK]
Hint: Always close files after writing to save data [OK]
Common Mistakes:
Forgetting to close the file
Calling SD.begin() after opening file
Misunderstanding FILE_WRITE mode
5. You want to write multiple sensor readings to a file on the SD card, but only if the SD card initializes successfully. Which of the following code snippets correctly implements this logic?
hard
A. if (SD.begin()) {
File dataFile = SD.open("readings.txt", FILE_WRITE);
if (dataFile) {
dataFile.println(sensorValue);
dataFile.close();
}
} else {
Serial.println("SD init failed");
}
B. File dataFile = SD.open("readings.txt", FILE_WRITE);
if (dataFile) {
if (SD.begin()) {
dataFile.println(sensorValue);
}
dataFile.close();
}
C. if (!SD.begin()) {
Serial.println("SD init failed");
} else {
File dataFile = SD.open("readings.txt");
dataFile.println(sensorValue);
dataFile.close();
}
D. SD.begin();
File dataFile = SD.open("readings.txt", FILE_WRITE);
dataFile.println(sensorValue);
dataFile.close();
Solution
Step 1: Check SD initialization before file operations
The correct code first calls and checks SD.begin() before attempting to open the file.
Step 2: Proper file open, write, close, and error handling
Open with SD.open("readings.txt", FILE_WRITE), verify with if (dataFile), write dataFile.println(sensorValue), dataFile.close(), and print error if init fails.
Final Answer:
if (SD.begin()) {
File dataFile = SD.open("readings.txt", FILE_WRITE);
if (dataFile) {
dataFile.println(sensorValue);
dataFile.close();
}
} else {
Serial.println("SD init failed");
} -> Option A
Quick Check:
Check SD.begin() first, then open, write, close file [OK]
Hint: Always check SD.begin() before file operations [OK]
Common Mistakes:
Opening file before SD.begin()
Not closing file after writing
Ignoring SD initialization failure
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.