EEVblog Electronics Community Forum

Products => Computers => Programming => Topic started by: NW27 on January 28, 2021, 08:53:53 pm

Title: Arduino String questions
Post by: NW27 on January 28, 2021, 08:53:53 pm
Good Morning,

I'm using the ESP32 and VScode PlatformIO IDE and I have a couple of String related questions:
1. What is the difference between "String" and "string"? I can declare variables with either
- String test1 = "test1";
- string test2 = "test2";

2. The below printLocalTime function sends out the required DateTime on the serial port.
I would like to have this as a global string.
After looking on the web, the below Print::print function was put forward but I do not understand a) how to call this and b) how it returns a string

Code: [Select]
size_t Print::print(struct tm * timeinfo, const char * format)
{
    const char * f = format;
    if(!f){
        f = "%c";
    }
    char buf[64];
    size_t written = strftime(buf, 64, f, timeinfo);
    print(buf);
    return written;
}
void printLocalTime()
{
  struct tm timeinfo;
  if(!getLocalTime(&timeinfo)){
    Serial.println("Failed to obtain time");
    return;
  }
  Serial.println(&timeinfo, "%Y-%m-%d %H:%M:%S");
}

Title: Re: Arduino String questions
Post by: ledtester on January 28, 2021, 09:17:59 pm
Based on this discussion:

https://forum.arduino.cc/index.php?topic=670228.0

"String" is a string class provided by the Arduino library. It allocates space for the string on the heap. Apparently it is a slimmed-down version of "std::string".

"string" is likely to be "std::string" which is the C++ class for strings. It also allocates space on the heap for storage.

"char *" is the basic C-style string. Constants are stored pre-allocated in global memory. Otherwise you have to allocate storage yourself.

Lots of routines like Serial.print accept either a "String" or "char *". Your "Print::print" function, however, only accepts a "const char*" argument. To convert a String to char* you can use either toCharArray() or getBytes() method. However, you will still need to provide space for the resultant C-style string, i.e. something like this:

Code: [Select]
size_t Print::print(..., String format) {

    char *format_buf[64];
    ...
    format.toCharArray(format_buf, 64);
    size_t written = strftime(..., format_buf, ...)
    ...

Note that in this example only the first 64 characters of the input String format will be passed to strftime.