Arduino UNO:在TF卡中创建并读写TXT文件

之前文章中写到Arduino的TF卡扩展,要做这个是因为一个项目要用TF卡存储信息,把收集到的数据存在一个txt文件里,之前提到CardInfo程序工作正常,输出了TF卡的相关信息,那么接下来,就继续完成创建并读写TXT文件的操作。

在IDE的例程中,有一个名为ReadWrite的例程,这个例程即可完成上述功能。

下面是程序源码:

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

源码解析:

首先,程序在Setup中就已经完成,loop中为空。

 Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

随后,进行SD卡的初始化。

 if (!SD.begin(4)) {//片选管脚初始化为4,若初始化失败,则返回值为0,输出initialization failed!
    Serial.println("initialization failed!");
    return;
  }

之后,我们打开名为TEXT.txt的文件,注意,如果SD卡中没有改文件则程序会自动创建。

  myFile = SD.open("test.txt", FILE_WRITE);

如果文件打开成功,向文件中写入testing 1, 2, 3.

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

写入完成后,文件关闭。再打开我们刚刚打开的txt文件,验证是否写入。

 while (myFile.available()) {
      Serial.write(myFile.read());//不停读取文件,并直接写到串口
    }

结果如下:

Initializing SD card...initialization done.
Writing to test.txt...done.
test.txt:
testing 1, 2, 3.
如果之前运行CardInfo程序没有问题,ReadWrite程序应当也能运行成功。




猜你喜欢

转载自blog.csdn.net/king_mountian/article/details/79641816