Arduino Uno SD卡模块 (二)读取文件

欢迎关注「凌顺实验室」微信公众号

 

 

 

 

 

实验效果

SD 卡根目录里有个文本文件 LingShunLAB.txt   

实验就是要打开它并且读取里面的数据

 

里面的内容如下:

hello world

    by LingShunLAB

 

 

在串口中显示文本内容

 

问题与注意

SDFat 库并不支持长文件名字,所以在程序中有要读取LingShunLAB.txt 这么长的文件名的时候,正确的打开方式是

LINGSH~1.TXT

 

 

BOM表

 

Arduiino Uno *1

SD卡模块  *1

SD卡   *1

调线若干

 

接线

 

Arduino Uno   <----->   Sd Card 模块

       GND          <----->           GND

        5V            <----->             +5

       CS            <----->            Pin 4

      MOSI         <----->           Pin 11

        SCK        <----->            Pin 13

      MISO         <----->           Pin 12

详细请参照 文章 Arduino Uno SD卡模块 (一)获取SDcard的信息 

 

 

开源程序

 

这个实验还是需要下载库

下载地址: https://github.com/greiman/SdFat

具体如何操作,再次说一下,下载解压到Arduino IDE的安装路径里的库文件夹libraries    

 

库里提供了很多SD卡模块示例程序,可以多多参考

 

 

 

//加载SPI库和SD库
#include <SPI.h>
#include <SD.h>

//声明文件对象
File myFile;

void setup() 
{
    Serial.begin(9600); //设置波特率
    while (!Serial) 
    {
    ; // wait for serial port to connect. Needed for native USB port only
      //等待串行端口连接。 仅适用于本机USB端口
    }
    
    Serial.print("Initializing SD card...");//正在初始化

    //如果返回4则初始化失败
    if (!SD.begin(4)) {
      Serial.println("initialization failed!");
      return;
    }
    Serial.println("initialization done.");//初始化结束

    myFile = SD.open("LINGSH~1.TXT");//打开指定文件
    if (myFile) {
      Serial.println("LingShunLAB.txt:");//串口输出test。txt
      Serial.println("↓↓↓↓");//串口输出↓↓↓↓
      // 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() {
  

}

 

 

 

 

 

 

程序实现思路解读

1

//加载SPI库和SD库
#include <SPI.h>
#include <SD.h>

2
//声明文件对象
File myFile;

 

3

myFile = SD.open("LINGSH~1.TXT");//打开指定文件

 

4

    if (myFile) {
      Serial.println("LingShunLAB.txt:");//串口输出test。txt
      Serial.println("↓↓↓↓");//串口输出↓↓↓↓
      // 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");
  }

  • 7
    点赞
  • 49
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值