Не могу прочитать SD-карту
У меня возникают ошибки при открытии файла на SD-карте. Вот инструкция, которую я использую: https://www.instructables.com/Micro-SD-Card-Tutorial/
/*
SD card read/write
This example shows how to read and write data to and from an SD card file
The circuit:
SD card attached to SPI bus as follows:
** MOSI - pin 11
** MISO - pin 12
** CLK - pin 13
** CS - pin 4 (for MKRZero SD: SDCARD_SS_PIN)
created Nov 2010
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe
This example code is in the public domain.
*/
#include <SPI.h>
#include <SD.h>
File myFile;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.print("Initializing SD card...");
if (!SD.begin(4)) {
Serial.println("initialization failed!");
while (1);
}
Serial.println("initialization done.");
// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
myFile = SD.open("test.txt", FILE_WRITE);
// if the file opened okay, write to it:
if (myFile) {
Serial.print("Writing to test.txt...");
myFile.println("testing 1, 2, 3.");
// close the file:
myFile.close();
Serial.println("done.");
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}
// re-open the file for reading:
myFile = SD.open("test.txt");
if (myFile) {
Serial.println("test.txt:");
// 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() {
// nothing happens after setup
}
Я вижу «Инициализация SD-карты...», «Инициализация выполнена» и «Ошибка открытия test.txt»
Можете ли вы помочь мне решить проблему?
@Gil Sven, 👍1
Обсуждение2 ответа
Лучший ответ:
Я добавил несколько задержек в код, и теперь он работает идеально.
/*
SD card read/write
This example shows how to read and write data to and from an SD card file
The circuit:
SD card attached to SPI bus as follows:
** MOSI - pin 11
** MISO - pin 12
** CLK - pin 13
** CS - pin 4 (for MKRZero SD: SDCARD_SS_PIN)
created Nov 2010
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe
This example code is in the public domain.
*/
#include <SPI.h>
#include <SD.h>
File myFile;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.print("Initializing SD card...");
if (!SD.begin(4)) {
Serial.println("initialization failed!");
while (1);
}
Serial.println("initialization done.");
delay(1000);
// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
myFile = SD.open("test.txt", FILE_WRITE);
delay(1000);
// if the file opened okay, write to it:
if (myFile) {
Serial.print("Writing to test.txt...");
myFile.println("testing 1, 2, 3.");
// close the file:
myFile.close();
Serial.println("done.");
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}
// re-open the file for reading:
myFile = SD.open("test.txt");
if (myFile) {
Serial.println("test.txt:");
// 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() {
// nothing happens after setup
}
Ваши контакты CS подключены неправильно, если задержки как-то помогают. то должно работать и без задержек., @Juraj
Я запустил ваш код без изменений на Arduino Uno, и он заработал с первого раза. Вывод:
Initializing SD card...initialization done.
Writing to test.txt...done.
test.txt:
testing 1, 2, 3.
Таким образом, проблема либо в самой SD-карте, либо в ваших подключениях к плате (или, полагаю, плата SD-карты может быть неисправна). Убедитесь, что карта отформатирована в FAT16 или FAT32. У меня FAT32, и проверьте, можно ли читать и записывать данные с неё с помощью ПК — просто перетащите на неё текстовый файл, нажав «Запись», и дважды щёлкните по нему, чтобы прочитать.
В соединениях, по сути, нет ничего плохого. Просто проверьте проводку. Для питания я использовал 5 В от платы Arduino.
- SD-карта не инициализируется
- Что означают эти контакты? Куда мне их подключить?
- Понимание того, почему следует избегать «String» и альтернативных решений
- Arduino: как записать значение переменной в текстовый файл и изменить его на SD-карте?
- Сохранение файла .txt на SD-карту и чтение данных каждого содержимого в файл txt, а затем сохранение его в переменной
- Простая веб-страница с Ethernet-шилдом Arduino на SD-карте
- Arduino: загрузка переменных со значениями, считанными с SD-карты
- чтение карты micro SD напрямую с ПК
запустите пример CardInfo. Это диагностический инструмент., @Juraj
Вы отформатировали карту в FAT32?, @fabiuz7