2

I want to write a function for my arduino project, but I have some issues.

char telephone_number = 111232113;
Serial.println("AT+CMGS=\"telephone_number\"\r");

Console is showing me AT+CMGS="telephone_number" but instead of this I want AT+CMGS="111232113" to be shown.

Is it even possible in this form? I'm new in programming and I don't know how to manage that.

tmthydvnprt
  • 10,398
  • 8
  • 52
  • 72
Piotr
  • 55
  • 1
  • 1
  • 7
  • 2
    This is a classic [question for google](https://www.google.com/search?q=arduino+combine+string+and+variable). Awesome that you are a new programmer! Keep going. You and google will become *very* good friends. Its knows more than anyone on Stack Overflow. :) – tmthydvnprt Mar 12 '16 at 23:10
  • Can this help? https://forum.arduino.cc/index.php?topic=649730.0 – Konrad Gajewski Jul 23 '20 at 18:50

2 Answers2

2

Don't use String. Temptingly easy to use, but you will eventually be sorry. :-( They are slower, use more RAM, and add 1.6k to your program size. Just stick with plain old C strings, also known as char arrays.

You can break your print statement up into three parts:

char telephone_number[] = "111232113";
Serial.print( "AT+CMGS=\"" );
Serial.print( telephone_number );
Serial.println( "\"\r" );

You can save even more RAM space by using the F macro around the print of double-quoted strings:

char telephone_number[] = "111232113";
Serial.print( F("AT+CMGS=\"") );   // Saves 10 bytes of RAM
Serial.print( telephone_number );
Serial.println( F("\"\r") );       // Saves 3 bytes of RAM

Any place you print a double-quoted string like that, just wrap it with the F macro.

BTW, I assume the telephone number(s) is not a constant, so you need to keep it in RAM, as the char array shown here.

slash-dev
  • 1,569
  • 2
  • 9
  • 9
1

You were almost there!

There are two points you need to fix:

  1. char telephone_number = 111232113;. The type char is usually used to keep a single character. In Arduino, you can to use the class String to represent multiple characters.

  2. In order to concatenate the value of a string variable with another string you need to use the operator +. See String Addition Operator.

Here is the corrected code:

String telephone_number = "111232113";
Serial.println("AT+CMGS=\"" + telephone_number + "\"\r");
Arton Dorneles
  • 1,629
  • 14
  • 18