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:
COM6
Hello
Arduino
Autoscroll
Clear output
9600 baud
Newline
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:
COM6
Hello
Arduino
Autoscroll
Clear output
9600 baud
Newline
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:
COM6
Hello
Arduino
Autoscroll
Clear output
9600 baud
Newline
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 |
Please note: These are Amazon affiliate links. If you buy the components through these links, We will get a commission at no extra cost to you. We appreciate it.