Hello, I know how to save the data to a SD Card if I specify the filename in advance using
myFilename = SD.open("file1.txt", FILE_WRITE);
Could you please let me know what to do if I want the user to enter the filename in the Serial Monitor and then use it to create a new file to write the data to?
Here is a conceptual explanation.
Change your hard coded filename to a variable.
Add code to ask for the filename
wait for a response
read the data
verify it appears to be a valid filename
assign that data to the variable in step 1.
The easiest approach is to modify your code to receive a string from the serial monitor. You'll then need to validate the string to ensure it is correct before processing it. Since I don't know your skill level or the tools available to you, I should mention this likely won't be a simple one or two evening project.
I know how to do it in C/C++ but not in Arduino. Is asking for user input acceptable under setup() rather than inside loop()?
In another project, I was able to get the user input from the serial terminal and then do some processing inside loop(). For entering of the filename and creating the file, is it OK to do it inside setup()?
Where and how you get your filename is… up to you.
Typically setup() is used for initialisation stuff, but there is no reason not to do anything that only needs be done once, at the beginning, right there.
Placed in the loop() or a function called from there, you could have some sort of condition that would make it ask you (again perhaps) for the filename when the need arose.
There is no right or wrong or better or worse about it.
Unlikely. The serial monitor has a small window in which you can type in a file name. Click on the window and start typing. Hit the "send" button when done.
I recommend that you read the Serial Input Basics tutorial linked above, and try the examples.
I tried Example2 and it worked. However, I want to know why my method of entering the file name using scanf in setup() does not work.
Here is the complete code:
When I executed the code, the Serial Monitor printed a bunch of square followed by Enter name. Then, it printed .txt without giving me a chance to enter the name in the Message field.
OK. In the else part of the while loop of Example 2, I opened the file with the file name I entered on the Serial Monitor. Although there was no error message, the program did not create the file. What is wrong?
It is a bit strange but after I added your checking code, it created a file on the SD card. Problem is why the resulting file name is made of capital letters even I entered lower case letters and the program confirmed this by printing the name in lower case letters on the Serial Monitor?
For help on this forum, please read and follow the instructions in the "How to get the best out of this forum" post, linked at the head of every forum category.