在連線到 Arduino 的 SD 卡中儲存新檔案
在本教程中,我們將建立一個新的檔案,該檔案儲存在連線到 Arduino Uno 的 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 → Datalogger 中訪問它。
或者,您可以在 GitHub 上訪問程式碼:https://github.com/adafruit/SD/blob/master/examples/Datalogger/Datalogger.ino 我們首先包含 SPI 和 SD 庫,並設定 chipSelect 引腳(我們將將其設定為 10)。
#include <SPI.h> #include <SD.h> const int chipSelect = 10;
在 Setup 中,我們初始化 Serial 和 SD 卡。
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..."); // see if the card is present and can be initialized: if (!SD.begin(chipSelect)) { Serial.println("Card failed, or not present"); // don't do anything more: while (1); } Serial.println("card initialized."); }
在迴圈中,我們從 3 個模擬引腳讀取資料,並將其儲存在名為 dataString 的字串中。然後,我們使用 SD.open() 函式以 FILE_WRITE 模式開啟檔案 datalog.txt。**此函式會在檔案不存在時建立檔案**。然後我們將新的 dataString 附加到檔案中並關閉檔案。標準命令 dataFile.println() 用於將資料附加到檔案。
void loop() { // make a string for assembling the data to log: String dataString = ""; // read three sensors and append to the string: for (int analogPin = 0; analogPin < 3; analogPin++) { int sensor = analogRead(analogPin); dataString += String(sensor); if (analogPin < 2) { dataString += ","; } } // open the file. note that only one file can be open at a time, // so you have to close this one before opening another. File dataFile = SD.open("datalog.txt", FILE_WRITE); // if the file is available, write to it: if (dataFile) { dataFile.println(dataString); dataFile.close(); // print to the serial port too: Serial.println(dataString); } // if the file isn't open, pop up an error: else { Serial.println("error opening datalog.txt"); } }
廣告