|
在一些Arduino应用程序中,能够实现在本地存储和检索信息是非常有优势的。您可以使用一张Secure Digital或SD卡实现此功能。 SD卡是一种非易失性存储卡,广泛应用于手机、数码相机、GPS导航设备、手持控制台和平板电脑等便携式设备中。另一种类型的SD卡是Micro SD卡。尺寸仅为15毫米x 11毫米x 1毫米,是最小的存储卡。它大小约为普通尺寸的SD卡的四分之一,大约为一个指甲的大小。
为了将Micro SD卡连接到Arduino Mega开发板,我们使用带有Micro SD卡插槽的以太网扩展板。另外,市场上有许多其他的扩展板可用于不同类型的SD卡。
如上图所示,一张micro SD卡有8个引脚。下表描述了每个引脚的功能。 引脚序号 | 名称 | 功能说明 | 1 | NC | 未连接 | 2 | CS | 片选/从选择(SS) | 3 | DI | 主输出/从输入(MOSI) | 4 | VDD | 电源电压 | 5 | CLK | 时钟(SCK) | 6 | VSS | 电源电压地 | 7 | DO | 主输入/从输出(MISO) | 8 | RSV | 保留 |
如果您要自己尝试连接到此SD卡,则必须确保将SD卡的引脚连接到Arduino的相应的引脚。由于我们使用的是商用的扩展板,所以这并不是个问题。我们所需要做的就是将Arduino的默认CS(片选)引脚声明为OUTPUT。它位于Arduino MEGA开发板上的第53引脚。在以太网扩展板上,CS引脚是第4引脚。您需要在代码中指定该引脚才能使SD卡正常工作。
实验1 在这个实验中,我们将学习如何从SD卡上读取文件。
所需的硬件材料 ● 1张Micro SD卡 ● 1个以太网扩展模块 ● 1个Arduino Mega2560开发板
代码 要从SD卡上读取文件,我们需要使用SD.h库。以下代码假定文件“ourfile.txt”已经写入到SD卡中。 - #include “SD.h”
- const int cs = 4;
- void setup()
- {
- Serial.begin(9600);
-
- Serial.print("Initializing card...");
- // make sure that the default chip select pin is declared OUTPUT
-
- pinMode(53, OUTPUT);
-
- // see if the card is present
- if (!SD.begin(cs))
- {
- Serial.println("Card failed to initialize, or not present");
-
- return;
- }
- Serial.println("card initialized.");
-
- // open the file named ourfile.txt
-
- File myfile = SD.open("ourfile.txt");
- // if the file is available, read the file
- if (myfile)
- {
- while (myfile.available())
- {
- Serial.write(myfile.read());
- }
- myfile.close();
- }
- // if the file cannot be opened give error report
- else {
- Serial.println("error opening the text file");
- }
- }
- void loop()
- {
- }
复制代码
实验2 在这个实验中,我们将学习如何在SD卡中创建一个文件,写入数据,然后从SD卡中读取数据。
所需的硬件 我们将使用与之前实验相同的硬件
代码 要将文件写入SD卡并读取该文件,我们需要再次使用SD.h库。 - #include “SD.h”
- File myfile;
- void setup()
- {
-
- Serial.begin(9600);
-
- Serial.print("Initializing card...");
-
- // declare default CS pin as OUTPUT
- pinMode(53, OUTPUT);
-
- if (!SD.begin(4)) {
- Serial.println("initialization of the SD card failed!");
- return;
- }
- Serial.println("initialization of the SDcard is done.");
-
-
- myfile = SD.open("textFile.txt", FILE_WRITE);
-
-
- if (myfile)
- {
- Serial.print("Writing to the text file...");
- myfile.println("Congratulations! You have successfully wrote on the text file.");
-
- myfile.close(); // close the file:
- Serial.println("done closing.");
- } else
- {
- // if the file didn't open, report an error:
- Serial.println("error opening the text file!");
- }
-
- // re-open the text file for reading:
- myfile = SD.open("textFile.txt");
- if (myfile)
- {
- Serial.println("textFile.txt:");
-
- // read all the text written on the file
- while (myfile.available())
- {
- Serial.write(myfile.read());
- }
- // close the file:
- myfile.close();
- } else
- {
- // if the file didn't open, report an error:
- Serial.println("error opening the text file!");
- }
- }
- void loop()
- {
- }
复制代码 |