In the Arduino IDE, go to "Sketch" > "Include Library" > "Manage Libraries..."
Search for and install the necessary libraries, such as "SD" for microSD card support and any libraries specific to your sensor (e.g., "DHT" for DHT11/DHT22 temperature and humidity sensors).
// Arduino Data Logger Tutorial
#include <SPI.h>
#include <SD.h>
// Define the pins for the sensor
const int sensorPin = A0;
// Define the file name for the data log
const char* fileName = "datalog.txt";
// Variables to store sensor data
float sensorData;
// The setup function runs once at the beginning of the program
void setup() {
// Start serial communication to view data on the Serial Monitor
Serial.begin(9600);
// Initialize the microSD card
if (!SD.begin()) {
Serial.println("Card initialization failed!");
return;
}
// Create or open the data log file
File dataFile = SD.open(fileName, FILE_WRITE);
// If the file is successfully opened, write the header
if (dataFile) {
dataFile.println("Sensor Data");
dataFile.close();
} else {
Serial.println("Error opening file!");
}
}
// The loop function runs repeatedly after the setup function has finished
void loop() {
// Read data from the sensor
sensorData = analogRead(sensorPin);
// Convert analog reading to actual sensor value (if needed)
// e.g., sensorData = map(sensorData, 0, 1023, 0, 100);
// Print the sensor data to the Serial Monitor
Serial.print("Sensor Data: ");
Serial.println(sensorData);
// Log the sensor data to the microSD card
logData(sensorData);
// Wait for a specific duration (adjust as needed)
delay(5000); // 5 seconds
}
// Function to log data to the microSD card
void logData(float data) {
// Open the data log file in append mode
File dataFile = SD.open(fileName, FILE_WRITE);
// If the file is successfully opened, write the data
if (dataFile) {
dataFile.println(data);
dataFile.close();
} else {
Serial.println("Error opening file!");
}
}
Make sure your Arduino board is still connected to your computer via the USB cable. Click the "Upload" button (the right arrow icon) in the Arduino IDE to upload the code to the Arduino board.
After uploading the code, open the Serial Monitor (Tools > Serial Monitor) to view the sensor data being printed. The data will also be logged to the microSD card in the "datalog.txt" file.
You have successfully created an Arduino Data Logger. The sensor data is being logged to the microSD card, allowing you to collect and analyze data over time.
Remember to modify the code to match your specific sensor and data logging requirements. You can also add more sensors or additional data to the log file as needed.