How to use Arduino String.toCharArray() function to convert a string to a char

If you are a newb like me you are probably confused on how to use the String.toCharArray() method. I sure wish the docs had a nice example right there showing how to use it.
It took me a while to figure out how to properly pass a string to a function. Then I needed to convert that string to a char type to be able to pass it to a u8g2 method to print it to a tiny little .96 inch screen.

tiny paper meme

It seemed like no matter what I passed to the following method :

u8g2.drawStr(0, 40, char_array);

I would get some sort of error in the compiler about some sort of conversion this or that. I tried everything and found all the wrong ways. The most confusing part was creating the buffer. It would be nice if the docs contained info or an example on how to create the buffer. So I searched the googlenet and the first example I found was all about arduino and it was all wrong too. So I angrily kept searching the googlenet

Searching the GoogleNet with lots of bad words.

Then I found an example that worked. YAY, https://www.tutorialspoint.com/convert-string-to-character-array-in-arduino.

Here is a nice little example of a function that accepts a string, but needs it to be a char type for the u8g2 methods to work.

void sendToScreen(String ipAddress) {
  u8g2.firstPage();
  //this creates a buffer
  char char_array[ipAddress.length()];
  //this actually does the conversion
  //this has to go here not in the function below
  ipAddress.toCharArray(char_array, ipAddress.length() + 1); 
  do {
    u8g2.setFont(u8g2_font_helvB12_tr);
    u8g2.drawStr(0, 20, "Ip Address is");
    //now it can print the value passed to the function
    u8g2.drawStr(0, 40, char_array);
  } while (u8g2.nextPage());
}

I’ll never complain about the verbosity of Java again. LOL

And you have to put the toCharArray() call on a separate line for some stupid reason even if you add char before it, you can’t call it in the method like so or it gives you a special error.

invalid use of void expression
   20 |     u8g2.drawStr(0, 40, ipAddress.toCharArray(char_array, ipAddress.length() + 1));
      |                         ~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
baby what does that even mean meme
What does this error mean?

So you have to do the method call on a separate line like the code above. That doesn’t make sense to me, but I am just a C++/Arduino newb There is probably some magical C++ syntax that lets you call the function within the function, but I don’t know it. I thought Scala (*_*) <–(perfectly valid function name) was confusing, but working with Strings in C++ is more confusing. LOL

Maybe next I’ll write an article about how to pass a String to a function and use it with u8g2 library to print to a tiny .96 inch oled screen. LOL


Posted

in

,

by

Tags:

Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.