How to pass string to function in Arduino

How to pass a string to a function in Arduino?

Answer

There are two types of string: String() object and char array.

For String object

You just need to pass String type. For example:

void myFunction(String myString) { Serial.println(myString); } String string_1 = "Hello"; String string_2 = "Arduino"; void setup() { Serial.begin(9600); myFunction(string_1); myFunction(string_2); } void loop() { }

The output on Serial Monitor:

Newbiely | Arduino IDE 2.3.8
──
File
Edit
Sketch
Tools
Help
Arduino Uno
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Uno' on 'COM15')
New Line
9600 baud
Hello Arduino
Ln 11, Col 1
Arduino Uno on COM15
2

For Char Array

There are two ways to pass char array to a function on Arduino

  • Pass char array by Array Type
  • Pass char array by Pointer Type

Pass Char Array to a Function by Array Type

Example code

void myFunction(char myString[], int length) { for (byte i = 0; i < length; i++) { Serial.print(myString[i]); } Serial.println(); // add a new line } char string_1[] = "Hello"; char string_2[] = "Arduino"; void setup() { Serial.begin(9600); myFunction(string_1, sizeof(string_1) - 1); // - 1 because of null character myFunction(string_2, sizeof(string_2) - 1); // - 1 because of null character } void loop() { }

The output on Serial Monitor:

Newbiely | Arduino IDE 2.3.8
──
File
Edit
Sketch
Tools
Help
Arduino Uno
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Uno' on 'COM15')
New Line
9600 baud
Hello Arduino
Ln 11, Col 1
Arduino Uno on COM15
2

Pass Char Array to a Function by Pointer Type

Example code

void myFunction(char *myPointer, int length) { for (byte i = 0; i < length; i++) { Serial.print(*(myPointer + i)); } Serial.println(); // add a new line } char string_1[] = "Hello"; char string_2[] = "Arduino"; void setup() { Serial.begin(9600); myFunction(string_1, sizeof(string_1) - 1); // pass via a pointer myFunction(string_2, sizeof(string_2) - 1); // pass via a pointer } void loop() { }

The output on Serial Monitor:

Newbiely | Arduino IDE 2.3.8
──
File
Edit
Sketch
Tools
Help
Arduino Uno
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Uno' on 'COM15')
New Line
9600 baud
Hello Arduino
Ln 11, Col 1
Arduino Uno on COM15
2

See references:

Buy Arduino

1 × Arduino UNO Buy on Amazon
1 × USB 2.0 cable type A/B Buy on Amazon
1 × Jumper Wires Buy on Amazon
Disclosure: Some links in this section are Amazon affiliate links. If you make a purchase through these links, we may earn a commission at no extra cost to you.
Additionally, some links direct to products from our own brand, DIYables .

The Best Arduino Starter Kit

※ OUR MESSAGES