项目
用Arduino从SD卡上读写文件
2015年6月23日通过蒂姆血性小子在一些Arduino应用程序中,能够本地存储和检索信息是非常有利的。你可以使用安全的数码或SD卡来实现这一点。SD卡是一种非易失性存储卡,广泛应用于移动设备,如手机、数码相机、GPS导航设备、掌上游戏机和平板电脑。另一种类型的SD卡是Micro SD卡。只有15mm × 11mm × 1mm,是最小的存储卡。它只有普通SD卡的四分之一大小,或者指甲盖大小。
你可以在Arduino系统中使用SD卡来存储和检索信息
在一些Arduino应用程序中,能够本地存储和检索信息是非常有利的。你可以使用安全的数码或SD卡来实现这一点。SD卡是一种非易失性存储卡,广泛应用于移动设备,如手机、数码相机、GPS导航设备、掌上游戏机和平板电脑。另一种类型的SD卡是微SD卡。只须测量15毫米x11毫米x1毫米,即t是最小的存储卡。它只有普通SD卡的四分之一大小,或者指甲盖大小。
为了将micro SD卡连接到我们的Arduino Mega上,我们将使用带有micro SD插槽的以太网屏蔽。然而,对于其他类型的SD卡,有许多不同的护盾可供选择。
如图所示,micro - SD卡有8个引脚。下表描述了每个引脚的功能。
销名称描述
1 NC未连接
2 CS芯片选择/从选择(SS)
3 DI Master Out/Slave In (MOSI)
4 VDD电源电压
5 CLK时钟(SCK)
6 VSS供电电压接地
掌握进/从(味噌)
8 RSV保留
如果您尝试自己接口这个SD卡,则必须确保将SD卡的引脚连接到Arduino的适当引脚上。因为我们使用的是商用的防护盾,所以这不是问题。我们需要做的就是将Arduino的默认CS (chip select)引脚声明为输出。这是Arduino MEGA上的53号引脚。在以太屏蔽上,CS引脚为引脚4。你需要在SD卡正常工作的代码中指定这个。
实验1
在这个实验中,我们将学习如何从SD卡读取文件。
硬件要求
- 1个micro - SD卡
- 1 ×以太网屏蔽模块
- 1 x Arduino Mega2560
代码
要从SD卡读取,我们将使用SD.h库。这段代码假设文件“ourfile.txt”已经被写入SD卡。
#include const int cs = 4;void setup() {Serial.begin(9600);系列。打印(“初始化卡…”);//确认默认的芯片选择引脚是声明的//查看卡是否存在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() { }
实验2
在这个实验中,我们将学习如何创建一个文件,写它,然后从SD卡读取它。
硬件要求
我们将使用与之前实验相同的硬件
代码
为了向SD卡写入文件并读取该文件,我们将再次使用SD.h库。
#include File myfile;void setup() {Serial.begin(9600);系列。打印(“初始化卡…”);//声明默认的CS pin为输出if (!SD.begin(4)) {/ / SD卡初始化失败返回;}系列。println(" SDcard初始化完成"); 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() { }
视频
自己尝试一下这个项目吧!BOM。
你好,我想问一下在哪里可以找到和下载SD.h库。谢谢你!