Author Topic: Arduino String questions  (Read 2597 times)

0 Members and 1 Guest are viewing this topic.

Offline NW27Topic starter

  • Regular Contributor
  • *
  • Posts: 53
  • Country: au
Arduino String questions
« 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");
}

« Last Edit: January 28, 2021, 08:57:54 pm by NW27 »
 

Online ledtester

  • Super Contributor
  • ***
  • Posts: 4225
  • Country: us
Re: Arduino String questions
« Reply #1 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.
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf

 

- - -
-->