Arduino sprintf()Arduino sprintf

Serial communication is one of the most commonly used forms of communication in Arduino. It enables the board to communicate with a computer or another devices. In some instances, you might have to transmit a string or a sequence of characters from Arduino to the connected device. Reading strings from serial input on Arduino can become confusing for beginners.

Step 1: Define the String Variable

First of all we need some variable to store the incoming string from serial port. We can do the reading process in traditional character array type string or we can also make use of String class available in Arduino core. For the character array, the array size must be enough to hold for the maximum number of characters plus the null character. For example, if you expected your string to be 10 characters long then you should define the variable as follows:

char receivedChar[11];
Code language: C++ (cpp)

Step 2: Read the String

Now its time when your are ready to read the string, you can simply do character by character until you found your delimiter character. Which could be a new line feed character \n or line break character or any character of your choice. First of all check if characters are available to read from the serial port with the help of Serail.available() function. If there are characters you can read one character into a char variable like this.

while (Serial.available()>0) {
  char incomingChar = Serial.read();
}Code language: JavaScript (javascript)

The above code will read one character at a time from the Serial port. However, you have to loop the above line of code until you receive a null character (“\n”) or your desired string length. You can do this with following code.

void loop() {
  char inChar = 0;
  static int i = 0; // static ensures the variable retains its value between function calls

  if (Serial.available() > 0) {
    inChar = Serial.read();

    if (inChar != '\n') {
      receivedChar[i++] = inChar;

      // Check if the buffer is full to avoid overflow
      if (i >= sizeof(receivedChar) - 1) {
        i = 0; // Reset the index if the buffer is full
      }
    } else {
      // Process the received string or reset if needed
      receivedChar[i] = '\0'; // Null-terminate the string
      Serial.print("Received: ");
      Serial.println(receivedChar);

      // Clear the buffer for the next string
      memset(receivedChar, 0, sizeof(receivedChar));

      // Reset the index
      i = 0;
    }
  }
}

Code language: Arduino (arduino)


There is another approach of doing the same thing which is as follows.

char receivedChar[11];
int i=0;

void setup() {
Serial.begin(9600);
}
void loop() {
while (Serial.available()>0) {
   char incomingChar = Serial.read();
   receivedChar += incomingChar;
   i++;
   if (incomingChar == '\n' || i==10) {
      Serial.print("Received: ");
      Serial.println(receivedChar);
      memset(receivedChar, 0, sizeof (receivedChar));
      i=0;
   }
  }
}
Code language: Arduino (arduino)

Step 3: Read String with readStringUntil

There is Arduino serial read string until newline method available in the Serial library. We can make use of that function and provide any character to wait for until we done reading. Make sure to set the timeout with Serial.setTimeout(10); You can find more about this function from the following link.

https://www.arduino.cc/reference/tr/language/functions/communication/serial/readstringuntil/

readStringUntil() reads characters from the serial buffer into a String. The function terminates if it times out (see setTimeout()).

Here is the code example to read the string untill a character found.

String input;
int number;
void setup() {
  Serial.begin(9600);
  Serial.setTimeout(50); // about 1mS/char at 9600baud
}

void loop(){
 if (Serial.available()) {
    input = Serial.readStringUntil('\n');
    if (input.length() > 0) {  // got some new input
      input.trim(); // remove delimiters
     Serial.print(input);
    }
}
Code language: Arduino (arduino)

By Abdul Rehman

My name is Abdul Rehman and I love to do Reasearch in Embedded Systems, Artificial Intelligence, Computer Vision and Engineering related fields. With 10+ years of experience in Research and Development field in Embedded systems I touched lot of technologies including Web development, and Mobile Application development. Now with the help of Social Presence, I like to share my knowledge and to document everything I learned and still learning.

Leave a Reply

Your email address will not be published. Required fields are marked *

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