Hi all. Have been googling since last night and I just can't find the correct solution for this. I know it is a simple thing, but without C experience ( only VB ) I just don't understand why this seems to be so complicated.
Yes, I know the answers are out there, but I've been hunting for hours and just can't get this resolved. Please help.
The bottom line of what I am trying to do, is to pass a string to a function (void PRtxt) and have that function work with the passed string.
Final use would be to join strings for Serial.println, or for writing to an SD card, etc.
Questions:
Is it correct in the setup() to join strings using . & or + ?
Is it correct to pass the String to PRtxt, or does it first need to be converted to a char array ?
In the PRtxt function, can I join a char and a string ( String sLine = pTxt . " doesn't exist."; ) ?
OK. Have just found sprintf. I think this may hold the solution.
Should the following work, or will I again get conflicts between the 'char' received by the 'MKfile' function and the String I want to join to it ?
#include <SD.h>
#include <stdio.h>
const int chipSelect = 4;
void MKfile(char fName[])
{
char buffer [100];
int n;
if (SD.exists(fName)) {
n=sprintf (buffer, "%s %s", fName, " exists");
Serial.println(buffer);
}
else {
n=sprintf (buffer, "WARNING : %s %s", fName, " does NOT exist");
Serial.println(buffer);
}
// open a new file and immediately close it:
File myFile;
myFile = SD.open(fName, FILE_WRITE);
myFile.close();
// Check to see if the file exists:
if (SD.exists(fName)) {
n=sprintf (buffer, "The file : %s %s", fName, " exists");
Serial.println(buffer);
}
else {
n=sprintf (buffer, "WARNING : The file : %s %s", fName, " does NOT exist.");
Serial.println(buffer);
}
}
void setup(void)
{
Serial.begin(9600);
Serial.print("Initializing SD card...");
// make sure that the default chip select pin is set to output, even if you don't use it:
pinMode(10, OUTPUT);
// see if the card is present and can be initialized:
if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
return; // don't do anything more:
}
Serial.println("card initialized.");
MKfile("datalog.txt");
}
void loop(void)
{
}
So from your example, either your code or my code would work ?
Yes, but...
sprintf adds a tremendous amount of code to your sketch. You can use multiple Serial.print() statements to output all the data, without the overhead of the sprintf function.
sprintf() will work, and your code will work - but the code you're dealing with is very straightforward, and you can avoid sprintf if you wish to rearrange the message a bit:
Serial.print("Starting Sequence...");
Serial.print(fName);
if (SD.exists(fName))
Serial.print(" exists");
else
Serial.print(" DOES NOT EXIST");
or even
Serial.print("Starting Sequence...");
Serial.print(fName);
Serial.print( SD.exists(fName) ? " exists" : " DOES NOT EXIST" );