從連線到 Arduino 的 SD 卡讀取檔案
顧名思義,在本教程中,我們將從連線到 Arduino 的 SD 卡讀取檔案。
電路圖
電路圖如下所示:

如您所見,您需要進行以下連線:
| SD 卡座 | Arduino Uno |
|---|---|
| Vcc | 5V |
| GND | GND |
| MISO | 12 |
| MOSI | 11 |
| SCK | 13 |
| CS | 10 |
僅對於 Vcc,請確保您的 SD 卡座以 5V 作為輸入。如果它接受 3.3V,則將其連線到 Arduino Uno 上的 3.3V 引腳。
程式碼演練
我們將逐步介紹隨附內建 SD 庫的示例程式碼。您可以從檔案 → 示例 → SD → 讀取寫入中訪問它

或者,您可以在 GitHub 上找到程式碼:https://github.com/adafruit/SD/blob/master/examples/ReadWrite/ReadWrite.ino 如您所見,我們首先包含庫和檔案的建立物件。
#include <SPI.h> #include <SD.h> File myFile;
在 Setup 中,我們首先初始化 Serial,然後初始化 SD 卡。請注意,我們將 SD 卡的 chipSelect 連線到引腳 10 而不是 4。因此,我們將使用 10 作為 SD.begin() 中的引數初始化 SD,而不是 4。
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.print("Initializing SD card...");
if (!SD.begin(10)) {
Serial.println("initialization failed!");
while (1);
}
Serial.println("initialization done.");接下來,我們以 FILE_WRITE 模式開啟一個名為 test.txt 的檔案。請注意,如果這樣的檔案不存在,這將建立一個新的檔案 test.txt。然後我們向 test.txt 寫入一行並關閉檔案。
// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
myFile = SD.open("test.txt", FILE_WRITE);
// if the file opened okay, write to it:
if (myFile) {
Serial.print("Writing to test.txt...");
myFile.println("testing 1, 2, 3.");
// close the file:
myFile.close();
Serial.println("done.");
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}然後,我們重新開啟檔案,這次用於讀取(我們沒有向 SD.open() 提供第二個引數,因為預設模式是讀取模式。然後我們逐個字元讀取檔案,並在 Serial Monitor 上列印讀取的內容,然後關閉檔案。請注意,這裡的重要函式是 .available() 和 .read()。.available() 告訴我們是否還有任何內容要讀取,而 .read() 讀取下一個可用的字元。
// re-open the file for reading:
myFile = SD.open("test.txt");
if (myFile) {
Serial.println("test.txt:");
// read from the file until there's nothing else in it:
while (myFile.available()) {
Serial.write(myFile.read());
}
// close the file:
myFile.close();
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}
}迴圈中沒有執行任何操作。
void loop() {
// nothing happens after setup
}
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP