Writing user input from Serial Monitor to newly created file on SD Card

Hey there! I was hoping I could receive some help with trying to write to a new file on an SD card.

I am having trouble with trying to modify this code where I'm trying to allow the user to input text through the serial monitor which is then written to a newly created file on an SD card. I was hoping I could find out what mistakes are or how this is possible. I am using Arduino Uno and Nano.

The goal is for the user to open the serial monitor, type in a string of letters/numbers to input into the file, have a new line generated, repeat this process several times, and then on the last line when the user enters the last few inputs these are then separated only by a blank space. The loop has a fixed amount of iterations for our application.

Other details include creating the file, using a different file type then .txt (.info in our case), and closing the file.

 
  Serial.println("Creating box.info");
  
  myFile = SD.open("box.txt", FILE_WRITE);

    
  Serial.println("Enter input for box.info");

  while (counter < counterlimit){
   
    if(myFile) {
      if (counter >= 8){
        while(Serial.available()==0){}
        value = Serial.readString();
        myFile.println(value);
        myFile.println(" ");
        counter++;     
      }else {
        while(Serial.available()==0){}
        value = Serial.readString();
        myFile.println(value);
        myFile.println("\n");
        counter++;     
      }
    }
  }
  
    myFile.close();

On the serial monitor window, when I input something I don't see that text then returned in the window for me to see (Serial.println(value)) and the code gets stuck at the loop it seems (the rest of the code which I will share outputs fine when while (counter < counterlimit) is removed.

I tried

while (counter < counterlimit){
  serial.println("1");
 // break;
    if(myFile) {``

And the 1 will get continuously printed to the monitor without ending the loop so it seems like the if (MyFile) statement is not working.

Here is the rest of the code

#include <SPI.h>
#include <Wire.h>
#include "SdFat.h"
#include "FreeStack.h"
#include "DS1390_SPI.h"

SdFat SD;
/* Initialization_Check.ino
  
  Simple script to verify the RTC and SD Card connections
  - Displays all files stored in the SD Card, and allowing user to delete all files (excluding 'box.info').
    We only want new binary files on the SD Card when we receive it back from a deployment.
  - Loops the RTC's time to verify
 */


// SPI Settings (rising edge or falling edge)
SPISettings settingsA(8000000, MSBFIRST, SPI_MODE0); //rising edge (for ADC, POT, SD card)
SPISettings settingsB(8000000, MSBFIRST, SPI_MODE1); //falling edge (for DAC)

// SPI Chip Select Pins
const uint8_t POT_CS_PIN = 7;       //CS_SEL[2], PCB layout ####
const uint8_t SD_CD_PIN = 4;        //SD card reader chip-detected
const uint8_t SD_CS_PIN = A5;       //SD card chip-select pin, physically connected to pin A6 ####S


DS1390 Clock (1);
DS1390DateTime Time;



File myFile; // File Declaration

void setup() {
  // Open serial port

  
  Serial.begin(115200);
  digitalWrite(POT_CS_PIN, LOW); //CS for SPI DIGPOT, (also used for RTC and TEMP)
  pinMode(POT_CS_PIN, OUTPUT);
  SPI.begin();

  SdFat sd;
  SdFile dirFile;
  SdFile file;

  int AirboxByte = 0; // Character being added to box.info file
  
  String value = ""; // Value read by user
  int counterlimit = 11; // Count for the serial monitor loop
  int counter = 0;
  char value_byte = 0;

  
  uint16_t FileCount = 0;
  uint16_t dirIndex[300]; // Position of file's directory entry.
  
  if (!sd.begin(SD_CS_PIN, SD_SCK_MHZ(50))){
    sd.initErrorHalt();
  }
  
  Serial.println("Creating Airbox.info");
  
  myFile = SD.open("Airbox.txt", FILE_WRITE);

    //while (option != 'y'){
  Serial.println("Enter input for Airbox.info");

  while (counter < counterlimit){
  serial.println("1");
 // break;
    if(myFile) {
      Serial.println("2");
      if (counter >= 8){
        Serial.println("3");
        while(Serial.available()==0){}
        value = Serial.readString();
        Serial.println("4");
        Serial.println("erger");
        myFile.println(value);
        myFile.println(" ");
        counter++;     
      }else {
        while(Serial.available()==0){}
        value = Serial.readString();
        Serial.println("ret444");
        myFile.println(value);
        myFile.println("\n");
        counter++;     
      }
    }
  }
  
    myFile.close();
  
  if(dirFile.open("/", O_READ)){
    Serial.println("SD card contains:");
    while (file.openNext(&dirFile, O_READ)){
      if(file.isHidden()){
      }else{
        file.printName(&Serial);
        Serial.println();
      }file.close();
    }
    Serial.println("Would you like to erase files from the SD card (excluding AirBox.info)? (y/n): ");
    int input = 3;
    while(input != 110 && input != 121){
      while(!Serial.available()){}
      input = Serial.read();
    }
    if(input == 110){
      Serial.println("Keeping files on the SD card");
    }else{
      Serial.println("Removing files from the SD card");
      SdFile dirFile;
      if (!sd.begin(SD_CS_PIN, SD_SCK_MHZ(50))){
        sd.initErrorHalt();
      }
      dirFile.open("/", O_READ);
      int DeleteCount = 0;
      int MaxNameSize = 30;
      while(file.openNext(&dirFile, O_RDWR)){
        if(file.isHidden()){
        }else{
          char f_name[MaxNameSize+1];
          file.getName(f_name,MaxNameSize);
          f_name[MaxNameSize] = 0;
          if(strcmp(f_name,"AirBox.info")){ //If file name is NOT "AirBox.info"
            if(!file.remove()) Serial.println("Error file remove");
            DeleteCount++;
          }
        }file.close();
      }Serial.print("Deleted ");
      Serial.print(DeleteCount);
      Serial.println(" files.");
    }
   }else{
    Serial.println("SD card empty");
  }
}

void printDirectory (SdFile CFile, int numTabs, uint16_t dirIndex[300], int FileCount){
  SdFile file;
  while (file.openNext(&CFile, O_READ)){
    if (file.isHidden()||false){
      //file hidden, skip
    }
    else{
      for (uint8_t i = 0; i < numTabs; i++){
        Serial.print('\t');
      }
      if (file.isSubDir()){
        SdFile SubDirFile;
        //Serial.print(file.dirIndex());
        //Serial.write(' ');
        //file.printName(&Serial);
        //Serial.println();
        if(SubDirFile.open(&CFile, file.dirIndex(), O_READ)){
          printDirectory(SubDirFile, numTabs+1, dirIndex, FileCount);
        }
      }
      else{
        // Save dirIndex of file in directory.
        dirIndex[FileCount] = file.dirIndex();
        // Print the file number and name.
        FileCount++;
        Serial.print(FileCount);
        Serial.write(' ');
        file.printName(&Serial);
        Serial.println();
      }
    }
    file.close();
  }
  Serial.println("RTC time:");
}

void loop() {
  Clock.getDateTimeAll (Time); //update clock
  char CurrentTime[] = {char(Time.Day / 10 + 48), char(Time.Day % 10 + 48), '-', char(Time.Month / 10 + 48), char(Time.Month % 10 + 48), '-', char(Time.Year / 10 + 48), char(Time.Year % 10 + 48),
                  '_', char(Time.Hour / 10 + 48), char(Time.Hour % 10 + 48), '-', char(Time.Minute / 10 + 48), char(Time.Minute % 10 + 48), '-', char(Time.Second / 10 + 48), char(Time.Second % 10 + 48)};
  Serial.println(CurrentTime);
  delay(1000);
}

Thank you!

Hi novaPharma,

welcome to the arduino-user-forum.

it is nice to say "thank you"

But what is your question? You haven't written a clear question.
You just posted some details of the code behaviour.

As a general recommendation divide the functionality in smaller parts.

Write a smaller programm that does nothing more than read in one line of user-input and that prints that one single line to the serial monitor

And read through how the function readstring() works.
The details of how this function works are crucial !

best regards Stefan

As @StefanL38 mentioned the knowledge about the functions used is crucial.

Sorry this is wrong, actually it is true, but intended "In the quoted part for example your code will only enter and then stay in the While() loop if and while nothing is available at Serial. Is this your intention?"

(I have to use my glasses :wink: )

However the identation misled me to assume it ends below counter++

as the while-loop has empty opening and closing curly brackets - without having tested it this while-loop keeps the code inside the while-loop until userinput is sended.

best regards Stefan

You are right of course (see above) :wink:

P.S.: That bis interesting: The identation is not there in the original, but when I copy it into code tags, the editor does it ...

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.