Snprintf question

I'm trying to learn different ways to build strings, etc. and have this little bit of code that I've been playing with.

#include <SD.h>                      // SD library
#include <TMRpcm.h>          //  also need to include this library...
#include <SPI.h>

#define SD_ChipSelectPin 10  

TMRpcm audio;   // create an object for use in this sketch

char filename [13]; 
char tunes [6] = "TESTR1";

void setup(){

  audio.speakerPin = 9; // speaker output pin
  
  Serial.begin(9600);
 
  snprintf (filename, 13, "\"%06s.WAV\"", tunes);
  Serial.print("File name:  ");
  Serial.println(filename);
  // audio.play (filename); 

  }

void loop(){  
  
  
 
}

What's interesting is that when I run this code (with audio.play (filename)) commented out, I get the first two entries in the monitor. If I remove the comments and execute the audio.play command, I get the third and fourth entries.

Screen Shot 2022-01-12 at 8.08.48 PM

So, two questions:

  1. Why does the code appear to have been run twice? (Serial.print outputs come up twice.)
  2. Why are the last 4 characters corrupted by executing the audio.play command?

Thanks.

7 bytes are required to store 6 characters plus the zero terminator. Just leave out the "6" and the compiler will allocate the correct amount of space for the string.

Why do you include double quote characters in a file name?

char filename [13]; 
char tunes [] = "TESTR1";

void setup(){
  Serial.begin(9600);
  snprintf (filename, 13, "%s.WAV", tunes);
  Serial.print("File name:  ");
  Serial.println(filename);
  }

void loop(){  }

Interesting. Removing the "6" got rid of the corruption issue, although I'm still not sure why the audio.play command caused the problem in the first place.

As for the double quotes - no reason, I was just playing.

Any idea why the setup seems to run twice?

Thanks.

If Serial Monitor is open when you upload a new sketch, it will run once. If it is closed when you upload it and then open Serial Monitor, the DTR line (part of the COM port) gets pulled low twice during initialization and that causes the board to reset after initial open so you see double.

Thanks for the explanation.

And your specification of %06s doesn't really mean anything since strings are not padded with leadng zeros, that only applies to numbers. The 6 is the minimum number of characters, not the maximum. The maximum is defined by the length of the string passed in, e.g. tunes

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