Consider this Arduino code that writes to an SD card and prints a message to the Serial Monitor. What will be printed on the Serial Monitor?
#include <SPI.h> #include <SD.h> const int chipSelect = 10; void setup() { Serial.begin(9600); while (!Serial) {} if (!SD.begin(chipSelect)) { Serial.println("Initialization failed!"); return; } File dataFile = SD.open("log.txt", FILE_WRITE); if (dataFile) { dataFile.println("Test data"); dataFile.close(); Serial.println("Write successful"); } else { Serial.println("Error opening file"); } } void loop() {}
Think about what happens if the SD card initializes correctly and the file opens successfully.
If the SD card initializes and the file opens for writing, the program writes "Test data" and prints "Write successful" to the Serial Monitor.
When connecting an SD card module to an Arduino Uno, which pin is typically used as the chip select (CS) pin?
Look for the pin that SPI devices commonly use as chip select on Arduino Uno.
Pin 10 is the default chip select pin for SPI devices like SD cards on Arduino Uno.
Examine the code below. It compiles but does not write data to the SD card. What is the most likely reason?
#include <SPI.h> #include <SD.h> const int chipSelect = 10; void setup() { Serial.begin(9600); if (!SD.begin()) { Serial.println("SD init failed"); return; } File file = SD.open("data.txt", FILE_WRITE); if (file) { file.println("Hello"); file.close(); Serial.println("Data written"); } else { Serial.println("Failed to open file"); } } void loop() {}
Check the SD.begin() function call and its parameters.
SD.begin() requires the chip select pin number to initialize the SD card properly. Omitting it causes initialization failure.
Which of the following code snippets will cause a compilation error when trying to write "Data" to a file on the SD card?
Check the constants used for file modes in the SD library.
FILE_WRITE is the correct constant for opening a file for writing. WRITE is undefined and causes a compilation error.
Given the code below runs on an Arduino with a working SD card, how many lines will the file "log.txt" contain after setup() finishes?
#include <SPI.h> #include <SD.h> const int chipSelect = 10; void setup() { Serial.begin(9600); while (!Serial) {} if (!SD.begin(chipSelect)) { Serial.println("SD init failed"); return; } for (int i = 0; i < 3; i++) { File file = SD.open("log.txt", FILE_WRITE); if (file) { file.println(i); file.close(); } } } void loop() {}
Consider how many times the file is opened and written to in the loop.
The loop runs 3 times, each time opening the file in append mode (FILE_WRITE) and writing one line, so the file will have 3 lines.