所有关于电路
项目

使用Arduino读取和写入SD卡的文件

2015年6月23日经过蒂姆杨ood

在一些Arduino应用程序中,能够本地存储和检索信息是非常有利的。你可以使用安全的数码或SD卡来实现这一点。SD卡是一种非易失性存储卡,广泛应用于移动设备,如手机、数码相机、GPS导航设备、掌上游戏机和平板电脑。另一种类型的SD卡是Micro SD卡。只有15mm × 11mm × 1mm,是最小的存储卡。它只有普通SD卡的四分之一大小,或者指甲盖大小。

你可以在Arduino系统中使用SD卡来存储和检索信息

在一些Arduino应用程序中,能够本地存储和检索信息是非常有利的。你可以使用安全的数码或SD卡来实现这一点。SD卡是一种非易失性存储卡,广泛应用于移动设备,如手机、数码相机、GPS导航设备、掌上游戏机和平板电脑。另一种类型的SD卡是SD卡。仅测量15毫米x 11 mm x 1 mm,it是最小的存储卡。它只有普通SD卡的四分之一大小,或者指甲盖大小。

SD卡
SD卡


要将Micro SD卡连接到我们的Arduino Mega,我们将使用带有Micro SD插槽的以太网屏蔽。但是,许多不同的屏蔽可用于其他类型的SD卡。

针

如上图所示,Micro SD卡具有8个引脚。下表描述了每个引脚的功能。

PIN名称描述

1 NC未连接

2 CS芯片选择/从选择(SS)

3 DI Master Out/Slave In (MOSI)

4 VDD电源电压

5 CLK时钟(SCK)

6 VSS供电电压接地

7做/奴隶的掌握(味噌)

8 RSV保留

如果您自己尝试互相接地,您必须确保将SD卡的引脚连接到Arduino的相应销钉。由于我们正在使用商业上可用的盾牌,这不是一个问题。我们需要做的只是将Arduino的默认CS(芯片选择)引脚声明为输出。这是我们的Arduino Mega上的PIN 53。在以太网屏蔽上,CS引脚是PIN编号4.您需要在SD卡的代码中指定此项以正常工作。

实验1

在这个实验中,我们将学习如何从SD卡中读取文件。

硬件要求

  • 1 x Micro SD卡
  • 1 x以太网屏蔽模块
  • 1 x Arduino Mega2560
Arduino MEGA安装以太网屏蔽


代码

要从SD卡读取,我们将使用SD.h库。这段代码假设文件“ourfile”。已写入SD卡。

# include < SD。h> const int cs = 4;void setup() {Serial.begin(9600);serial.print(“初始化卡......”);//确认默认的芯片选择引脚是声明的//查看卡是否存在if (!SD.begin(cs)) {初始化失败,或者不存在卡片返回;}系列。println(“卡初始化。”);//打开名为ourfile.txt的文件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() { }

ready_and_writing.zip.

实验2

在这个实验中,我们将学习如何创建文件,写入文件,然后从SD卡读取它。


硬件要求

我们将使用与之前的实验相同的硬件


代码

为了向SD卡写入文件并读取该文件,我们将再次使用SD.h库。

#include 文件myfile;void setup() {Serial.begin(9600);serial.print(“初始化卡......”);//声明默认CS引脚作为输出Pinmode(53,输出);if(!sd.begin(4)){serial.println(“SD卡的初始化失败!”);返回;serial.println(“SDCard的初始化完成”。);myfile = sd.open(“textfile.txt”,file_write);if(myfile){serial.print(“写入文本文件......”);myfile.println(“恭喜!你在文本文件上成功写了。”); 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() { }

ready_and_writing.zip.

视频

自己尝试一下这个项目吧!得到bom。

2评论