最新消息:

Arduino库教程-SD-Read Write

Arduino 少儿编程 1769浏览 0评论
Arduino库教程

用 SD library 来读写一个 SD 卡上的文件

  • 这个例子显示了如何在SD卡上读取和写入数据。请点击这里了解更多关于SD卡的信息。

硬件要求

  • Arduino or Genuino board
  • Ethernet Shield (或者其他有SD插槽的开发板)
  • 格式化后的 SD 卡

电路

Arduino库教程-SD-Read Write
图由 Fritzing 绘制

  • Arduino或genuino板必须连接到 Ethernet Shield,并且也有连接到计算机的USB电缆。

原理图

Arduino库教程-SD-Read Write
图由 Fritzing 绘制

样例代码

  • 下面的代码被配置为使用一个Ethernet shield,上面有一个板上SD卡插槽。在setup()里,调用SD.begin(),命名pin4为CS引脚。此引脚的变化取决于你正在使用的shield或开发板的制作。

  • 在setup()里,用SD.open()创建一个名为 "test.txt"的新文件。FILE_WRITE使能对文件进行读写访问,结束时开始。如果一个文件"test.txt"已经在卡里,这个文件可以被打开。

  • 命名一个被打开的文件为"myFile"

  • 一旦被打开,用myFile.println()将字符串写入卡片,后面跟着一个回车。一旦内容被写入,关闭文件。

  • 再次,用SD.open()打开该文件。一旦打开,用SD.read()让Arduino读文件的内容,并发送他们到串口。读取所有文件的内容后,用SD.close()关闭文件。

/*
  SD card read/write

 This example shows how to read and write data to and from an SD card file
 The circuit:
 * SD card attached to SPI bus as follows:
 ** MOSI - pin 11
 ** MISO - pin 12
 ** CLK - pin 13
 ** CS - pin 4

 created   Nov 2010
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe

 This example code is in the public domain.

 */

#include <SPI.h>
#include <SD.h>

File myFile;

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(4)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

  // 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");
  }

  // 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
}

[Get Code]
更多

  • SD library – SD 卡库的参考网页.

  • Notes on using SD cards – 当你使用SD卡时,你需要知道什么

  • Datalogger – 如何把三个模拟传感器的数据记录到SD卡。

  • DumpFile – 怎样从SD卡里读取一个文件。

  • Files – 怎样创建和删除一个SD卡文件。

  • Listfiles – 怎样将SD卡上的目录中的文件打印出来。

  • ReadWrite – 怎样从一个SD卡里读取或写入文件

您必须 登录 才能发表评论!