Arduino Libary: SD
範例程式: ReadWrite
說明
The library supports FAT16 and FAT32 file systems on standard SD cards and SDHC cards.
配置單位大小與所占空間有關,如單位大小16KB,若存在一個5KB的檔案,仍占用16KB儲存空間.
相對的,若單位大小越大,讀寫的速度會越快.
1. 硬體連接
2. 主要函式說明
if (!SD.begin(4)) // 如果回傳值不等於1 代表初始化失敗
File myFile; //宣告myFile是一個檔案
myFile = SD.open("test.txt", FILE_WRITE); //以寫入模式開啟檔案
寫入檔案
if (myFile) { //判斷檔案是否存在
myFile.println("testing 1, 2, 3."); // close the file:
myFile.close(); //關閉檔案
}
else { // if the file didn't open, print an error:
}
讀取檔案
myFile = SD.open("test.txt"); 以讀取模式開啟檔案
if (myFile) { //判斷檔案是否存在
while (myFile.available()) { // 若還有可讀取的資料
Serial.write(myFile.read());
}
myFile.close(); //關閉檔案
}
操作函式
SD class
SD.begin() //初始化SD函示庫及SD卡 SD.begin(cspin)
SD.exists() //檢查指定的資料夾或檔案是否存在 SD.exists(filename)
SD.mkdir() //建立資料夾 SD.mkdir(dir_name)
SD.open() //開啟資料夾或檔案 SD.open(filepath) (若檔案不存在會自動建立)
SD.remove() //刪除檔案 SD.remove(filename)
SD.rmdir() //刪除資料夾 SD.rmdir(dir_name)
File class
file.name() // 回傳檔案名稱 file.name()
file.available() // 檢查檔案是否有可讀取的有效資料
file.peek() // 關閉檔案且確保寫入修改的資料儲存到 SD 卡
file.flush() // 檔案關閉時會自動確實寫入修改的資料存到 SD 卡
file.peek() // Read a byte from the file without advancing to the next one.
file.position() // 取得文件正在寫入的位置
file.print() // Print data to the file, which must have been opened for writing. Prints numbers as a sequence of digits, each an ASCII character
file.print(data) file.print(data, BASE)
BASE (optional): the base in which to print numbers: BIN for binary (base 2), DEC for decimal (base 10), OCT for octal (base 8), HEX for hexadecimal (base 16).
file.println() // Print data, followed by a carriage return and newline, to the File, which must have been opened for writing.
file.println() file.println(data) file.print(data, BASE)
data (optional): the data to print (char, byte, int, long, or string)
BASE (optional): the base in which to print numbers: BIN for binary (base 2), DEC for decimal (base 10), OCT for octal (base 8), HEX for hexadecimal (base 16)
file.seek() // Print data, followed by a carriage return and newline, to the File, which must have been opened for writing.
file.seek(pos)
file.size() // 取得檔案大小 file.size()
file.read() // 讀取檔案資料 file.read() file.read(buf, len)
file.write() // 寫入資料到檔案 file.write(data) file.write(buf, len)
file.isDirectory() // 判斷開啟的檔案是否為資料夾 file.isDirectory()
file.openNextFile() //
file.rewindDirectory() //
參考連結