You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Arduino SD卡代码无法查找/创建文件 运行报错问题求助

问题根源

代码存在初始化逻辑冲突、两套操作接口混用的问题:

  • 先调用了无参数的SD.begin(),该方法默认使用核心预设的CS引脚(多数Arduino核心默认是10号引脚,并非你定义的4号引脚)初始化SD卡,后续又单独调用card.init()用4号CS引脚初始化自定义的底层卡对象,两次初始化参数不一致,状态冲突。
  • 全局定义的Sd2Card card、SdVolume volume、SdFile root是独立于SD库内部维护的实例,手动初始化自定义的card对象,不会同步更新SD类的内部状态。Cardinfo示例是直接操作这三个底层对象实现卡信息读取,所以单独跑能正常识别SD卡,但后续调用SD.exists()、SD.open()用的是SD类的上层接口,读取的是错误初始化的内部实例状态,自然无法查找、打开、创建文件。
修复方案

删除冗余的底层对象定义,统一使用SD库标准流程初始化,修改后的可运行代码如下:

#include <SPI.h>
#include <SD.h>

const int chipSelect = 4;
String IPRange = "192.168.1.";
String port = "21";

void setup() {
  Serial.begin(115200);
  Serial.print("Initializing SD card...");

  // 传入CS引脚参数统一初始化,不再单独调用card.init
  if (!SD.begin(chipSelect)) {
    Serial.println("initialization failed. Things to check:");
    Serial.println("* is a card inserted?");
    Serial.println("* is your wiring correct?");
    Serial.println("* did you change the chipSelect pin to match your shield or module?");
    while (1);
  } else {
    Serial.println("Wiring is correct and a card is present.");
  }

  ListIP(); 
}

void loop() {
  // 无循环逻辑留空即可
}

void ListIP() {
  if (SD.exists("ip.txt")) {
    Serial.println("IT DOES EXIST");
  } else {
    Serial.println("IT IS GONE?!");
  }
  File dataFile = SD.open("ip.txt", FILE_WRITE);
  if (dataFile) {
    dataFile.println("FTP Server: ");
    dataFile.print(IPRange);
    dataFile.print(" ");
    dataFile.print(port);
    dataFile.close();
    Serial.println("Write to ip.txt completed.");
  } else {
    Serial.println("error opening ip.txt");
  }
}
额外排查点

如果替换代码后仍有问题,逐一检查以下项:

  • SD卡必须格式化为FAT32文件系统,分配单元大小不超过32KB,禁止使用exFAT、NTFS格式,Arduino自带SD库默认不支持这两类文件系统。
  • 容量超过32GB的SD卡无法用自带SD库正常驱动,需要替换为第三方SdFat库使用。
  • 确保SPI接线正确:除CS引脚接4号外,MISO、MOSI、SCK要对应接开发板的硬件SPI引脚,SD模块供电要稳定,供电不足会导致文件读写异常。
  • 不需要在打开文件后加冗余的delay(100),只要SD.open()返回有效文件对象,就可以直接执行读写操作。

内容的提问来源于stack exchange,提问作者Frederik A.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.01 20:18:30