Consider the following Arduino code snippet initializing SPI for an SD card module. What will be printed on the Serial Monitor?
void setup() {
Serial.begin(9600);
if (!SD.begin(10)) {
Serial.println("Initialization failed!");
} else {
Serial.println("Initialization done.");
}
}
void loop() {}Check if the SD card module is connected correctly and the chip select pin matches.
If the SD card is not connected or the chip select pin is wrong, SD.begin() returns false, printing "Initialization failed!".
SPI communication has four modes (0 to 3) defined by clock polarity and phase. Which mode is standard for SD card modules?
SD cards use SPI mode where clock idles low and data is sampled on the rising edge.
SD cards use SPI Mode 0, where clock polarity is 0 (idle low) and clock phase is 0 (data sampled on rising edge).
Examine the code below that attempts to write "Hello" to a file on the SD card. Why does it fail to save the data?
#include <SPI.h> #include <SD.h> File myFile; void setup() { Serial.begin(9600); if (!SD.begin(10)) { Serial.println("SD init failed"); return; } myFile = SD.open("test.txt", FILE_WRITE); if (myFile) { myFile.print("Hello"); Serial.println("Write done"); myFile.close(); } else { Serial.println("Error opening file"); } } void loop() {}
Think about what happens after writing to a file on SD cards.
Data is buffered and only saved when the file is closed. Missing myFile.close() causes data loss.
Look at the code snippet below. What error will it cause when compiled?
byte data = SPI.transfer();
Check the required parameters for SPI.transfer().
SPI.transfer() requires one byte argument to send. Calling it without arguments causes a compile error.
Given the code below, how many files will be created on the SD card after running setup() once?
#include <SPI.h> #include <SD.h> void setup() { Serial.begin(9600); SD.begin(10); for (int i = 0; i < 3; i++) { String filename = "file" + String(i) + ".txt"; File f = SD.open(filename.c_str(), FILE_WRITE); if (f) { f.println("Data " + String(i)); f.close(); } } } void loop() {}
Look at the loop and how filenames are generated.
The loop runs 3 times creating 3 different files with names file0.txt, file1.txt, and file2.txt.
