Go Down

Topic: Sketch will only write files when the Serial Port is opened (Read 1 time) previous topic - next topic


Hello all,

I've written a sketch to be part of a bigger sketch.
Assuming there is no files in the SD to begin with, the sketch creates empty text files in the form "x.text", where x is a integer,
x is generated from an incrementer in the loop function.

The strange thing is that this only works when I've opened the serial monitor, to me based on my limited experience it shouldn't happen? It's not like I'm doing the logical (if Serial =="True"){evalute the rest of the code}", or am I?.

Reason for me asking is that I would like to initiate the loop using a pushbutton, and If I can't because it would only initialize when I open the serial monitor, then yeah I'd probably have a problem.

Here is the code:

Code: [Select]

/* This code demonstrates what happens when
you write multiple .csv files with the same name
repeatedly in the SD directory

#include <SD.h>

const int SSPin = 10; // Hardware SS pin

void setup() {
  while (!Serial){
    ; // wait for serial port to connect. Needed for Leonardo only
  Serial.print("Initializing SD card...");
  pinMode(SSPin, OUTPUT); 
  if (!SD.begin(4)) {
  Serial.println("initialization failed!");
  else {
  Serial.println("initialization done.");

void loop() {
  // Local Var
  static int count = 0;
  char fileName[8];

  //Count and char/string conversions
  String fileNumber = String(count) + ".txt";
  fileNumber.toCharArray(fileName, 8);

  //Create File
  File myFile = SD.open(fileName, FILE_WRITE);



Code: [Select]
  while (!Serial){
    ; // wait for serial port to connect. Needed for Leonardo only

If you are leaving this code in when you don't start the serial monitor it may never gat past this point.

It would be useful for you to post the code with and without serial initialisation.
Arduino Libraries https://github.com/MajicDesigns?tab=Repositories
Parola for Arduino https://github.com/MajicDesigns/Parola
Arduino++ blog https://arduinoplusplus.wordpress.com

Go Up