I am using a mega to get data from sensors and trying to write to a SD card, so the wiring is
SS 10 53
MOSI 11 51
MISO 12 50
SCK 13 52
The module I used is SUNFOUNDER SD card module
Amazon:https://www.amazon.com/SunFounder-Module-Socket-Reader-Arduino/dp/B01G8BQV7A
Here is my code:
/*
Writing Sensor Data to an SD card
//
This example shows how to write data
to an SD card using the SD library.
//
The circuit:
- SD card attached to SPI bus as follows:
** MOSI - pin 11
** MISO - pin 12
** CLK - pin 13
** CS - pin 10 Uno (53 on Mega)
SPI Uno Mega
SS 10 53
MOSI 11 51
MISO 12 50
SCK 13 52*/
//
#include <SD.h>
#include <SPI.h>
//
//the hardware CS pin (10 on most Arduino boards,
// 53 on the Mega) must be left as an output or the SD
// library functions will not work.
const int CSpin = 53;
String dataString =""; // holds the data to be written to the SD card
float sensorReading1 = 1.00; // value read from your first sensor
float sensorReading2 = 2.00; // value read from your second sensor
float sensorReading3 = 3.00; // value read from your third sensor
File sensorData;
//
//
void setup()
{
// Open serial communications
Serial.begin(9600);
Serial.print("Initializing SD card...");
pinMode(CSpin, OUTPUT);
//
// see if the card is present and can be initialized:
if (!SD.begin(CSpin)) {
Serial.println("Card failed, or not present");
// don't do anything more:
return;
}
Serial.println("card initialized.");
}
//
void loop(){
// build the data string
dataString = String(sensorReading1) + "," + String(sensorReading2) + "," + String(sensorReading3); // convert to CSV
saveData(); // save to SD card
delay(6000); // delay before next write to SD Card, adjust as required
}
//
void saveData(){
sensorData = SD.open("data.csv", FILE_WRITE);
if (sensorData){
sensorData.println(dataString);
sensorData.close(); // close the file
}
}
The setup function is ok, after I plug in the SD card, it displays "card initialized." and started to write to files. But after I unplug the SD card and plug it into my PC to check the data, it was full of unreadable files, and I couldn't even open it.
Any ideas?