Files

80 lines
2.1 KiB
Arduino
Raw Permalink Normal View History

2023-03-17 11:59:21 +00:00
/*
SD card datalogger
This example shows how to log data from three analog sensors
2026-03-20 17:18:15 +00:00
to an SD card using the SD library. Pin numbers reflect the default
SPI pins for Uno and Nano models
2023-03-17 11:59:21 +00:00
The circuit:
2026-03-20 17:18:15 +00:00
analog sensors on analog pins 0, 1, and 2
2023-03-17 11:59:21 +00:00
SD card attached to SPI bus as follows:
2026-03-20 17:18:15 +00:00
** SDO - pin 11
** SDI - pin 12
2023-03-17 11:59:21 +00:00
** CLK - pin 13
2026-03-20 17:18:15 +00:00
** CS - depends on your SD card shield or module.
Pin 10 used here for consistency with other Arduino examples
(for MKR Zero SD: SDCARD_SS_PIN)
2023-03-17 11:59:21 +00:00
created 24 Nov 2010
2026-03-20 17:18:15 +00:00
modified 24 July 2020
2023-03-17 11:59:21 +00:00
by Tom Igoe
This example code is in the public domain.
*/
#include <SPI.h>
#include <SD.h>
2026-03-20 17:18:15 +00:00
const int chipSelect = 10;
2023-03-17 11:59:21 +00:00
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
2026-03-20 17:18:15 +00:00
// wait for Serial Monitor to connect. Needed for native USB port boards only:
while (!Serial);
2023-03-17 11:59:21 +00:00
Serial.print("Initializing SD card...");
if (!SD.begin(chipSelect)) {
2026-03-20 17:18:15 +00:00
Serial.println("initialization failed. Things to check:");
Serial.println("1. is a card inserted?");
Serial.println("2. is your wiring correct?");
Serial.println("3. did you change the chipSelect pin to match your shield or module?");
Serial.println("Note: press reset button on the board and reopen this Serial Monitor after fixing your issue!");
while (true);
2023-03-17 11:59:21 +00:00
}
2026-03-20 17:18:15 +00:00
Serial.println("initialization done.");
2023-03-17 11:59:21 +00:00
}
void loop() {
// make a string for assembling the data to log:
String dataString = "";
// read three sensors and append to the string:
for (int analogPin = 0; analogPin < 3; analogPin++) {
int sensor = analogRead(analogPin);
dataString += String(sensor);
if (analogPin < 2) {
dataString += ",";
}
}
// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
File dataFile = SD.open("datalog.txt", FILE_WRITE);
// if the file is available, write to it:
if (dataFile) {
dataFile.println(dataString);
dataFile.close();
// print to the serial port too:
Serial.println(dataString);
}
// if the file isn't open, pop up an error:
else {
Serial.println("error opening datalog.txt");
}
}