Ova

How to save data in text file in Arduino?

Published in Arduino Data Logging 8 mins read

You can save data generated by your Arduino projects into a text file using two primary methods: by capturing its serial output on a connected computer or by directly writing data to an SD card interfaced with the Arduino board.

Method 1: Saving Arduino Serial Data to a Text File on a Computer

This method involves transmitting data from your Arduino via its USB (serial) connection to a computer, where a software program can then capture and save it as a text file. This approach is excellent for real-time monitoring, debugging, or when a standalone data logger isn't strictly necessary.

How it Works

  • Your Arduino sends data using Serial.print() or Serial.println() through its USB cable to the connected computer.
  • A program on the computer (such as the Arduino IDE's Serial Monitor, a dedicated terminal emulator, or a custom script) receives this incoming serial data.
  • The received data is then recorded and saved into a .txt file. For example, after capturing the data, you can save it as test.txt to store all the recorded information.

Steps to Capture and Save Serial Data

  1. Arduino Code Setup:

    • In your setup() function, initialize serial communication by calling Serial.begin(baudRate); (e.g., Serial.begin(9600);).
    • In your loop() function, use Serial.print(data); or Serial.println(data); to send the data you want to log.
    void setup() {
      Serial.begin(9600); // Start serial communication at 9600 baud rate
      Serial.println("Arduino Data Logger Started...");
    }
    
    void loop() {
      // Example: Send an analog sensor reading and a timestamp
      int sensorValue = analogRead(A0); // Read value from Analog pin A0
      long currentTime = millis();      // Get current time in milliseconds
    
      Serial.print("Time: ");
      Serial.print(currentTime);
      Serial.print(" ms, Sensor: ");
      Serial.println(sensorValue); // New line after sensor value
    
      delay(2000); // Log data every 2 seconds
    }
  2. Using Arduino IDE's Serial Monitor (Manual Copy-Paste):

    • Upload your sketch to the Arduino.
    • Open the Serial Monitor in the Arduino IDE (Tools > Serial Monitor).
    • Ensure the baud rate setting in the Serial Monitor matches the Serial.begin() value in your code.
    • Data will appear in the monitor window. To save it, select all the displayed text (usually Ctrl+A on Windows/Linux or Cmd+A on macOS), copy it (Ctrl+C or Cmd+C), and then paste it into any text editor (like Notepad, WordPad, VS Code, etc.). Finally, save the document as a .txt file (e.g., sensor_readings.txt).
  3. Using a Terminal Emulator (Automated Logging):

    • For more efficient and automated logging, use a dedicated terminal program that supports saving output to a file. Popular choices include PuTTY (Windows) or Termite (Windows). Linux/macOS users can use screen or minicom.
    • Steps for PuTTY (example):
      • Download and open PuTTY.
      • In the PuTTY configuration window, select Serial as the connection type.
      • Enter your Arduino's COM Port (you can find this in the Arduino IDE under Tools > Port).
      • Set the Speed (Baud Rate) to match the value you used in Serial.begin().
      • Navigate to the Session > Logging category in the left-hand menu.
      • Under "Session logging," choose the "Printable output" option and specify a filename for your log file (e.g., arduino_data_log.txt).
      • Click the Open button to start the connection. PuTTY will connect to your Arduino, and all incoming serial data will be automatically saved to the specified text file.

Pros and Cons of Serial Data Logging

Feature Pros Cons
Ease of Use Simple to set up with readily available tools. Requires a continuously connected computer.
Real-time Data can be monitored instantly as it's generated. Data logging ceases if the computer is disconnected or powered off.
Debugging Highly effective for troubleshooting and verifying code. Limited by the serial buffer size and communication speed.
Cost No additional hardware costs required. Not suitable for standalone, long-term data collection in remote areas.

Method 2: Saving Data Directly to an SD Card with Arduino

For applications requiring standalone data logging where your Arduino operates independently without a constant computer connection, using an SD card module is the most common and robust solution. This allows your Arduino to store sensor readings, timestamps, and other operational data directly onto a removable SD card.

Hardware Required

  • Arduino Board: (e.g., Arduino Uno, Mega, ESP32, ESP8266)
  • SD Card Module: These modules typically interface with Arduino using the Serial Peripheral Interface (SPI) communication protocol.
  • MicroSD or SD Card: It should be formatted as FAT16 or FAT32.
  • Jumper Wires: For connecting the module to your Arduino.

Wiring an SD Card Module (Common SPI Pins)

Most SD card modules connect to Arduino using the SPI interface. The specific pins might vary slightly based on your Arduino board, but typical connections are:

  • VCC: Connect to Arduino's 5V (or 3.3V for some modules/boards like ESP32).
  • GND: Connect to Arduino's GND.
  • CS (Chip Select): Connect to an Arduino digital pin (often pin 4 or 10, but can be user-defined).
  • MOSI (Master Out Slave In): Connect to Arduino Digital Pin 11 (on Uno/Nano), ICSP-4 (on Mega), or the dedicated MOSI pin on other boards.
  • MISO (Master In Slave Out): Connect to Arduino Digital Pin 12 (on Uno/Nano), ICSP-1 (on Mega), or the dedicated MISO pin.
  • SCK (Serial Clock): Connect to Arduino Digital Pin 13 (on Uno/Nano), ICSP-3 (on Mega), or the dedicated SCK pin.

(Always consult your specific SD card module's documentation for exact wiring instructions.)

Arduino Code for SD Card Logging

This method relies on the official Arduino SD library to manage interactions with the SD card.

  1. Include Libraries and Define CS Pin:

    #include <SPI.h> // Necessary for SPI communication
    #include <SD.h>  // The SD card library
    
    const int chipSelect = 10; // Define the CS pin for your SD card module
                               // (Commonly pin 4 or 10, adjust as needed)
  2. Initialize SD Card in setup():

    void setup() {
      Serial.begin(9600); // Initialize serial for debugging output
      while (!Serial) {
        ; // Wait for serial port to connect (needed for native USB port boards)
      }
    
      Serial.print("Initializing SD card...");
    
      // Check if the card is present and can be initialized
      if (!SD.begin(chipSelect)) {
        Serial.println("Card failed, or not present");
        while (true); // Halt execution if card fails to initialize
      }
      Serial.println("Card initialized.");
    }
  3. Write Data in loop():

    • Open a file: Use SD.open("filename.txt", FILE_WRITE); to open a file. If the file doesn't exist, it will be created. FILE_WRITE ensures that new data is appended to the end of the file if it already exists.
    • Write data: Use myFile.print() or myFile.println() to write your data.
    • Close the file: myFile.close(); is crucial after writing to ensure data is saved correctly and to prevent file corruption.
    void loop() {
      // Create a string to hold the data for logging
      String dataString = "";
    
      // Example: Read an analog sensor and append to the string
      int sensorReading = analogRead(A0);
      dataString += String(millis()); // Add current time as a timestamp
      dataString += ",";              // Use comma as a separator
      dataString += String(sensorReading);
    
      // Open the file. Only one file can be open at a time,
      // so you must close it before opening another.
      File dataFile = SD.open("datalog.txt", FILE_WRITE);
    
      // If the file was opened successfully, write to it:
      if (dataFile) {
        dataFile.println(dataString); // Write the data string followed by a newline
        dataFile.close();             // Close the file to save data
        Serial.println(dataString);   // Print to serial for debugging/monitoring
      }
      // If the file couldn't be opened, print an error:
      else {
        Serial.println("Error opening datalog.txt");
      }
    
      delay(5000); // Log data every 5 seconds
    }

Practical Tips for SD Card Logging

  • File Naming: To avoid overwriting data, consider implementing unique filenames for each logging session (e.g., LOG001.TXT, LOG002.TXT). You can use a counter or incorporate a timestamp if you have a Real-Time Clock (RTC) module.
  • Error Handling: Always include checks for SD.begin() and SD.open() return values to handle potential issues with the card or file access.
  • Power Consumption: SD card modules, especially during write operations, can draw significant current. Ensure your Arduino's power supply is sufficient.
  • Formatting: SD cards should typically be formatted as FAT16 or FAT32 for compatibility with the Arduino SD library.

Pros and Cons of SD Card Logging

Feature Pros Cons
Standalone Operates independently without requiring a computer connection. Requires additional hardware (SD card module, SD card).
Storage Offers high storage capacity (gigabytes) for extensive, long-term data logging. Setup and coding are generally more complex than serial output.
Portability Easy data transfer by simply removing the SD card. Risk of file corruption if power is lost during a write operation.
Cost Low cost per gigabyte of storage. Data retrieval often requires physically removing the card or adding a dedicated card reader.

Choosing the Right Method

  • Choose Serial Data Logging when:
    • You need to monitor data in real-time or for debugging purposes.
    • A computer is readily available and connected to the Arduino.
    • You don't need permanent, standalone data storage directly on the Arduino itself.
  • Choose SD Card Logging when:
    • Your Arduino must operate autonomously for extended periods.
    • You require large amounts of data storage capacity.
    • Data logging needs to occur in remote locations without a connected computer.
    • You desire easy, physical transfer of logged data.

Conclusion:
Saving data from your Arduino to a text file is achievable by either capturing its serial output on a computer or by writing directly to an SD card. Both methods are effective for data logging, with the optimal choice depending on your project's requirements for real-time monitoring, standalone operation, and storage capacity.