Writing on a file
Writing to a file using Arduino is similar to reading. For writing, we only need a few changes. We also need to open the file using SD.open()
, but this time we need to pass two arguments into this function; the file name and the file opening mode. So, our myFile
variable should be written as follows, after the card initialization is done. We will name our new file as myFile.txt
:
myFile = SD.open("myFile.txt", FILE_WRITE);
Here, FILE_WRITE
is the file mode. We need to pass this argument to open our file in writable mode. Now, if the file exists, we will print something using our File variable, which will be written on our myFile.txt file. After the writing is done, we will close the file to avoid any file corruption. Let's say we want to write the following lines on the myFile.txt
file:
Twinkle, twinkle, little star How I wonder what you are
We need to print the lines as follows:
myFile.println("Twinkle, twinkle, little star "); myFile.println("How I wonder what you are...