Skip to content

Commit 602ac64

Browse files
committed
Arduino SD Card example
1 parent 8b72061 commit 602ac64

File tree

1 file changed

+91
-0
lines changed

1 file changed

+91
-0
lines changed
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
// SPDX-FileCopyrightText: 2025 Liz Clark for Adafruit Industries
2+
//
3+
// SPDX-License-Identifier: MIT
4+
/*
5+
SD card read/write
6+
7+
This example shows how to read and write data to and from an SD card file
8+
The circuit:
9+
* SD card attached to SPI bus as follows:
10+
** MOSI - pin 35
11+
** MISO - pin 36
12+
** CLK - pin 34
13+
14+
created Nov 2010
15+
by David A. Mellis
16+
modified 9 Apr 2012
17+
by Tom Igoe
18+
modified 14 Feb 2023
19+
by Liz Clark
20+
modified 25 Aug 2023
21+
by Kattni Rembor
22+
modified 18 Feb 2025
23+
by Tim Cocks
24+
25+
26+
27+
This example code is in the public domain.
28+
29+
*/
30+
31+
#include <SPI.h>
32+
#include "SdFat.h"
33+
34+
#define SD_CS_PIN 39
35+
36+
SdFat SD;
37+
FsFile myFile;
38+
SdSpiConfig config(SD_CS_PIN, DEDICATED_SPI, SD_SCK_MHZ(16), &SPI1);
39+
40+
void setup() {
41+
// Open serial communications and wait for port to open:
42+
Serial.begin(115200);
43+
while (!Serial) { yield(); delay(10); } // wait till serial port is opened
44+
delay(100); // RP2040 delay is not a bad idea
45+
46+
Serial.print("Initializing SD card...");
47+
48+
// Retry mechanism for SD card initialization
49+
while (!SD.begin(config)) {
50+
Serial.println("initialization failed! Retrying...");
51+
delay(1000); // Wait for a second before retrying
52+
}
53+
Serial.println("initialization done.");
54+
55+
// open the file. note that only one file can be open at a time,
56+
// so you have to close this one before opening another.
57+
myFile = SD.open("test.txt", FILE_WRITE);
58+
59+
// if the file opened okay, write to it:
60+
if (myFile) {
61+
Serial.print("Writing to test.txt...");
62+
myFile.println("testing 1, 2, 3.");
63+
myFile.println("hello world!");
64+
// close the file:
65+
myFile.close();
66+
Serial.println("done.");
67+
} else {
68+
// if the file didn't open, print an error:
69+
Serial.println("error opening test.txt");
70+
}
71+
72+
// re-open the file for reading:
73+
myFile = SD.open("test.txt");
74+
if (myFile) {
75+
Serial.println("test.txt:");
76+
77+
// read from the file until there's nothing else in it:
78+
while (myFile.available()) {
79+
Serial.write(myFile.read());
80+
}
81+
// close the file:
82+
myFile.close();
83+
} else {
84+
// if the file didn't open, print an error:
85+
Serial.println("error opening test.txt");
86+
}
87+
}
88+
89+
void loop() {
90+
// nothing happens after setup
91+
}

0 commit comments

Comments
 (0)