Using Serial.read() with Arduino

Most people stumble across the Arduino Serial.read() function pretty early on in the Arduino learning curve.

Which makes sense!

Serial communication is a great way to see what’s going on after you compile and upload a new sketch, and it gets some early runs on the board. The problem is, a lot of coders then go off to learn all about the exciting stuff that goes beep and boop without getting a firm grasp of how serial communication really works and why it’s important.

Let’s fix that!

In this lesson, you’ll learn exactly how to use Serial.read() to receive data from the serial port and stitch it together as one value. We’ll cover this in two parts.

Part 1:

  • The big picture of serial communication
  • The serial buffer
  • Serial.read and Serial.available
  • Developing a protocol and strategy for reading in data from the serial port

Part 2:

  • Implementing the strategy in Arduino code
  • BONUS: How to convert the serial data from a string to an integer

The big picture of serial communication

Let’s take a step back from Serial.read(), and talk about serial communication.

What is serial data?

Serial communication is the process of sending one bit of data at a time, sequentially, from one place to another. For example, using serial data, you could send data from your Raspberry Pi to a connected Arduino, or vice versa.

How is serial data transferred?

USB is one of the most common ways to transmit serial communication — hence the name Universal Serial Bus. Using Arduino, we can easily send and receive data over a USB cable with the built-in Arduino Serial Library.

What is the Arduino Serial Library?

First, I’ll give you a quick rundown on libraries.

Programming Electronics Academy members, learn how to choose, install, and use Arduino libraries in the Arduino Course for Absolute Beginners Code Libraries section.

Not a member yet?  Sign up here.

An Arduino library is basically a bunch of code that has been bundled together to make your life easier. So, imagine you’re a barber, and you want to cut hair as efficiently as possible. A good way to do that would be to set up a drawer in your barber shop to hold all your hair-cutting tools in one place.

Every time a customer walks into your fine establishment for a haircut, all you need to do is open your drawer, and everything you need is right there in easy reach. And, of course, you may have a whole bunch of similar drawers. One might be for dying hair. Another might be for polishing the heads of bald folks to a high glossy shine.

It’s the same thing with Arduino libraries. Arduino libraries bring together a bunch of software functions that help you with specific tasks. The Arduino Serial library is just one of the many libraries you can use.

Serial Library Functions

So what tools live inside this library? The Serial library has functions like:

  • Serial.begin()
  • Serial.read()
  • Serial.available()
  • Serial.parseInt()
  • Serial.parseString()
  • Serial.parseFloat()
  • Serial.print()
  • Serial.captCrunch()

Don’t worry about what each of these functions does for now. Just bear in mind that the Serial.read() function is part of a larger Arduino Serial Library.

Programming Electronics Academy members, check out the Arduino Course for Absolute Beginners to practice using the Serial Library in your code.

Not a member yet?  Sign up here.

The Serial Buffer

OK, we know that serial communication over USB is how one device can talk to another. We also know that the Arduino Serial Library is a set of serial communication tools. But when data arrives at your Arduino, where does it go? The answer is the serial buffer — or more precisely, the serial receive buffer.

When bits of data start streaming in from your computer, a piece of hardware on your Arduino called a universal asynchronous receiver/transmitter (which can be shortened, thankfully, to UART) will assemble each of the 8 bits into a byte. The UART will then store those bytes (up to 64 bytes, in fact) in the serial receive buffer.

So, mystery solved. The data you send to your Arduino ends up in the serial receive buffer.

But then a new question bubbles up to the surface. Once the data is in the serial receive buffer, how do you access it?

This is where Serial.read() comes in.

Serial.read()

Serial.read()’s job, not all that surprisingly, is to read from the serial receive buffer. However, it’s important to understand that it reads in a very specific way. It’ll read out the first available byte from the serial receive buffer and then remove that byte from the buffer.

Let’s say you sent the phrase “Sub Sandwich” to your Arduino; this means you put 12 bytes into your serial receive buffer. Then let’s assume you typed the following code into a sketch.

char myFirstCharacter = Serial.read();

Serial.read() would scurry off to look at your phrase. It’d return the first available character in the serial receive buffer: A letter “S.” It’d leave “ub Sandwich” in the Serial receive buffer. Now the value “S” will be stored in the variable myFirstCharacter, and there will only be 11 bytes left in the serial buffer….

But what if we performed the same function again, this time entering the following code into a sketch:

char mySecondCharacter = Serial.read();

Now mySecondCharacter will be holding the value “u”, and “b Sandwich” is going to be left in the serial receive buffer.  You get the idea. Serial.read() takes one byte at a time from the serial receive buffer.

But before we move on, there’s a slight complication to consider

Now there is a little gotcha here that you need to look out for. When you’re sending data over serial, an invisible terminating character will often be added to the end of the transmission.

This could be a CR (Carriage Return) or a LF (Line Feed).  Both add an additional byte to the serial receive buffer. In fact, adding to the complexitudinosity (totally made up word), both a CR and an LF might be added, increasing your buffer size by two bytes. But don’t despair. There’s a workaround if you need it. Down at the bottom right of the Serial Monitor window, you’ll see options to either add these terminating characters every time you press the send button or omit them by selecting the No Line Ending option.

Whew, what a rollercoaster of discoveries this has been. Let’s move on shall we?

Serial.available() – the Serial Spy

Now’s a good time to introduce you to the nosy aunt of the serial communication world: Serial.available(). You can use this function to sniff out the serial receive buffer to see if there is anything in there available to read. The function will return the remaining bytes as a number value.

For example, imagine our whole phrase, “Sub Sandwich” is still sitting there in the serial receive buffer. Serial.available() would return the number 12 — that’s 1 for each remaining character in the buffer. If all you had in the serial receive buffer was “andwich” (I guess that’s like a bit more than half a sandwich?) then serial.available() would return the value 7.

Why is that useful?

Serial.available() is a quick and easy way to know if you have data in the serial receive buffer. The logic would look like this:

IF the return value of Serial.available() is greater than 0, THEN part of our message is still sitting in the serial receive buffer.

Does that mean you’re stuck dealing with one character at a time?

Thankfully, no. All this Serial.read() and Serial.available() stuff is great, but they’re not exactly convenient if you want to send the entire phrase “sub sandwich” to your Arduino and save it to a string. Nor are these functions ideal if you want to send a value like 462 to your Arduino and save that to an integer.

For these tasks, you’re far better off corraling all those bytes together into one string variable, or an integer, or whatever datatype floats your boat.

We’ll look at that next.

How to send integers, strings, or whatever over serial

OK, let’s roll up our sleeves and come up with a strategy…

Things are about to get a little technical here but don’t worry. You’ll have a blast!

And remember, if you are new to Arduino programming and want to learn how to do stuff just like this, then make sure to check out the Programming Electronics Academy membership. In our membership area we have video courses that walk you step-by-step through how to program Arduino. It’s a great resource to help you learn to prototype your own projects.

OK, back to our strategy…

First, we need to decide how we are going to send our data (which I will be calling “messages”) – that is, we need to decide on a protocol to follow.

Our Serial.read() protocol

Let’s make these the protocol rules that we’ll enforce in our Arduino program.

  • New messages will be read as soon as they arrive
  • Messages will be no longer than 12 bytes
  • Every message will end with a newline character ‘\n’ – which we will call our terminating character

This is a pretty basic protocol, but it will help us with our strategy.

First, we need a place to store the incoming bytes from the serial receive buffer. We can use a char array for that. Then we need to check if anything is even available in the serial receive buffer. We can use Serial.available to make that happen. Then we need to actually read in a byte. We have Serial.read() in our back pocket for that task.

Before we put the byte into our char array, we’ll need to check the incoming byte to make sure it is not a terminating character.

So here’s what that looks like when we lay it out as a list:

  1. Create a character array to store incoming bytes
  2. Check to see if there is anything in the serial receive buffer to be read – Serial.available()
  3. While there is something to be read then…
    • Read in the byte to a temporary variable – Serial.read()
    • Check to see if what we read is part of our message OR a terminating character
    • If it is part of our message, then save it to a character array
    • If it is a terminating character, then output the message and prepare for the next message
    • If the message has exceeded the max message length in the protocol, then stop reading in more bytes and output the message (or do something else with it).

Bare Minimum Arduino Sketch

Let’s get a bare minimum Arduino program started with setup() and loop(). We’ll add Serial.begin() to the loop to establish Serial Communication.

Notice in Serial.begin() we pass in the value 9600.  This is called the baud rate – it sets the speed of the serial communication, and represents bits per second. Both devices must have the same baud rate selected for Serial Communication to work.  If you’re using the Arduino IDE Serial Monitor window to send data, the baud rate can be set using a drop down menu.

void setup() {
  Serial.begin(9600);
}

void loop() {

}

Now let’s tackle the first step of our algorithm – we create a character array to hold the incoming message and a position variable to help us move through each element in the array. We’ll also create a constant to hold the max length of our message and use this to initialize the character array.

const unsigned int MAX_MESSAGE_LENGTH = 12;

void setup() {
 Serial.begin(9600);
}

void loop() {
 //Create a place to hold the incoming message
 static char message[MAX_MESSAGE_LENGTH];
 static unsigned int message_pos = 0;
}

Now we need to check if any bytes are available in the serial receive buffer. While there are, we need to read in the bytes and save them to a temporary variable. We can combine a while loop, Serial.available, and Serial.read() to make this happen.

const unsigned int MAX_MESSAGE_LENGTH = 12;

void setup() {
 Serial.begin(9600);
}

void loop() {

 //Check to see if anything is available in the serial receive buffer
 while (Serial.available() > 0)
 {
   //Create a place to hold the incoming message
   static char message[MAX_MESSAGE_LENGTH];
   static unsigned int message_pos = 0;

   //Read the next available byte in the serial receive buffer
   char inByte = Serial.read();
 }
}

Now we need to check to see if the byte we read is a terminating character or not… We can use an if-else statement for that. If it’s not a terminating character we’ll do one thing, and if it is a terminating character we’ll do something else.

//Message coming in (check not terminating character)
if ( inByte != '\n')
{
//Do Something
}
//Full message received...
else
{
//Do Something else
}

If it is part of our message, then save it to a character array. We’ll also need to increment our position in the char array for the next byte.

//Message coming in (check not terminating character)
if ( inByte != '\n')
{
 //Add the incoming byte to our message
 message[message_pos] = inByte;
 message_pos++;
}
//Full message received...
else
{
 //Do Something
}

Let’s take a closer look at what we are doing with the terminating character. If we do get the terminating character, that means we have received our entire message. We’re using the character to identify when we can actually do something with the message or data we received. In this example, we’ll print the message to the Serial Monitor window. We’ll also need to reset our character array to prepare for the next message.

//Full message received...
else
{
 //Add null character to string
 message[message_pos] = '\0';

 //Print the message (or do other things)
 Serial.println(message);

 //Reset for the next message
 message_pos = 0;
}

Before we can call this complete, we need to enforce the max message length in the protocol. This will prevent us from exceeding the space that we allotted in our character array. We can add this guard to our existing if statement.

if ( inByte != '\n' && (message_pos < MAX_MESSAGE_LENGTH - 1) )

Full Serial.read() Code

Here is the complete code to use Serial.read() to read in the entire message:

//Many thanks to Nick Gammon for the basis of this code
//http://www.gammon.com.au/serial

const unsigned int MAX_MESSAGE_LENGTH = 12;

void setup() {
 Serial.begin(9600);
}

void loop() {

 //Check to see if anything is available in the serial receive buffer
 while (Serial.available() > 0)
 {
   //Create a place to hold the incoming message
   static char message[MAX_MESSAGE_LENGTH];
   static unsigned int message_pos = 0;

   //Read the next available byte in the serial receive buffer
   char inByte = Serial.read();

   //Message coming in (check not terminating character) and guard for over message size
   if ( inByte != '\n' && (message_pos < MAX_MESSAGE_LENGTH - 1) )
   {
     //Add the incoming byte to our message
     message[message_pos] = inByte;
     message_pos++;
   }
   //Full message received...
   else
   {
     //Add null character to string
     message[message_pos] = '\0';

     //Print the message (or do other things)
     Serial.println(message);

     //Reset for the next message
     message_pos = 0;
   }
 }
}

OK, are you feeling a bit overwhelmed? When you’re starting out, this can feel like a ton of information to absorb, I know! Take your time, go back and read it a few times, and above all, be patient with yourself. If you return to this page after a bit more experimentation, there’s a great chance a lot of this stuff will just click into place.

Now before we call it quits with Serial.read(), I want to show you how to return this c string into an integer.

How to Convert a char to an Int with Arduino

What if instead of sending words or letters with the serial port, perhaps you are sending numerical values, like 42, or 314. How can you convert these digits into integers?

Well, there’s a super cool function called atoi(). This will take a null-terminated string and convert it to an integer.

Strings in the c programming language are null-terminated, meaning they end with the character ‘\0’.  The atoi() function will not work unless the string you pass in has the null-terminating character!

In our current code all we would have to do is add something like this:

else
{
 //Add null character to string
 message[message_pos] = '\0';

 //Print the message (or do other things)
 Serial.println(message);

 //Or convert to integer and print
 int number = atoi(message);
 Serial.println(number);

 //Reset for the next message
 message_pos = 0;
}

That’s it, now the serial message has been converted from a c string into an integer!

Review of Serial.read() Lesson

Let’s do a quick review.

First, we talked generally about Serial Communication – it’s a means of sending data ______________ .  We talked about the Serial Receive Buffer – do you remember how many bytes it can hold?

We discussed the basics of Serial.read() and Serial.available().

Serial.read() removes a byte from the ________________.  The function _________________ returns how many bytes are in the serial receive buffer.

We developed a simple _____________ and strategy for getting messages from our serial port.

Then we implemented the strategy in Arduino code. Finally, we talked about using the function atoi() to convert from a c string to an integer.

You made it!

If you liked this page, you’re going to love the next lesson. Next in this series, you’ll learn how to cut code down to just a couple of lines using some other built-in Serial library functions.

installing Arduino libraries

Installing Arduino Libraries | Beginners Guide

IoT sewage project

Pumping poo! An IoT sewage project

ESP32 webOTA updates

How to update ESP32 firmware using web OTA [Guide + Code]

error message Brackets Thumbnail V1

expected declaration before ‘}’ token [SOLVED]

Compilation SOLVED | 1

Compilation error: expected ‘;’ before [SOLVED]

Learn how to structure your code

32 Comments

  1. Richard Hayter on May 1, 2021 at 10:16 am

    Any thanks and appreciated. I need to focus and get the course completed!

    • Michael James on May 2, 2021 at 7:19 pm

      Thanks for watching Richard!

      • Giacomo on March 2, 2023 at 10:16 am

        la funzione atoi converte il carattete nel valore ascii?

        • Michael James on March 6, 2023 at 11:00 am

          Yes, that is correct. It determines what the ASCII value of the character is.

  2. Willem van Bergen on May 2, 2021 at 3:51 am

    Nice stuff!! but there is a little glitch in you text: the phrase ‘andwhich’ is 8 characters, not 7 (not counting the ”).

    • Michael James on May 2, 2021 at 7:19 pm

      Thanks Willem! I believe it is corrected now in the current video.

  3. Tanbirul Quadir Choudhury on June 27, 2021 at 12:42 pm

    Found the Write up as well the Youtube very informative and well put. Thanks a lot
    However in the program , why did you add the llines shown below in the Loop and not in the Setup

    //Create a place to hold the incoming message
    static char message[MAX_MESSAGE_LENGTH];
    static unsigned int message_pos = 0;

    • Michael James on June 27, 2021 at 8:20 pm

      Great question! It has to do with variable scope – this lesson might help clear it up:
      https://www.programmingelectronics.com/variable-scope/

      • Nick on August 6, 2021 at 5:44 pm

        It does seem like maybe those two lines should be above the while loop, like so:

        void loop() {
        static char message[MAX_MESSAGE_LENGTH];
        static unsigned int message_pos = 0;
        while(Serial.available()>0){
        //…………

        }
        }

        Otherwise wouldn’t the message and the message_pos get reset every time it tries to add the next character?

        • Michael James on August 6, 2021 at 7:26 pm

          Great question Nick! Since message[MAX_MESSAGE_LENGTH] and message_pos are “static”, they only get initialized once during the first time the loop runs. If they were not static, you are exactly correct, they would be written over each time.

  4. Brad O. on November 16, 2021 at 9:54 pm

    Isn’t there a problem with using that terminating character? If you use \n as the terminating character, it would mean that any time a value of 10 (ASCII translation) is sent, it would think it was the terminating character and abort. If you’re sending bytes of data across, you better be darn sure you don’t ever send a 10.

    • Michael James on November 17, 2021 at 10:12 am

      Hi Brad, great question! If I am not mistaken, when sending with the serial port, the decimal values are converted to ASCII for display. The ASCII character representation of 10 would be a “1” and a “0”, not the decimal value 10 refers to the decimal representation of a line feed in ASCII.

  5. Patrik on January 19, 2022 at 10:37 am

    Thanks!

  6. Sai on March 22, 2022 at 11:03 am

    how to send the serial port data to Ardunio

    • Michael James on March 23, 2022 at 10:31 am

      Hi Sai – great question! If you are using the Serial Monitor window in the Arduino IDE, at the top there is a text input spot, then you just press Enter and the data gets sent to the Arduino port that is selected. If you are using a different serial port monitor program on your computer, you would select the port that represents your target arduino.

  7. rené janssen on August 12, 2022 at 3:21 am

    Hi great stuff,
    I’m trying to send the data to my server but something goes wrong.
    I add a line after
    Serial.println(number);
    SendToServer(number);
    Then:
    bool SendToServer(message){
    HTTPClient http;
    char url[255];
    sprintf(url, “http://%s/process.php?data=%s”, serverIP, number);
    Serial.printf(“[HTTP] GET… URL: %s\n”,url);
    http.begin(url);
    etc etc

    my serial reads out a smart meter.
    thanks

    • Michael James on August 12, 2022 at 9:30 am

      Hi René, I am not sure I understand what is going wrong? Do you have an error message? Could you add some context to your question.

      • René Janssen on August 12, 2022 at 1:50 pm

        Hi Michael,
        I gues the whole telegram after reading is stored in “message or number” I want to send it to my server with
        bool SendToServer(number){
        HTTPClient http;
        char url[255];
        sprintf(url, “http://%s/process.php?data=%s”, serverIP, number);

        but i got compile errors
        Arduino:1.8.20 Hourly Build 2022/04/25 09:33 (Windows 10), Board:”LOLIN(WEMOS) D1 R2 & mini, 80 MHz, Flash, Disabled, All SSL ciphers (most compatible), 4M (no SPIFFS), v2 Lower Memory, Disabled, None, Only Sketch, 921600″
        dsmr:36:25: error: redefinition of ‘bool SendToServer’
        bool SendToServer(number){
        ^
        dsmr:36:6: error: ‘bool SendToServer’ previously declared here
        bool SendToServer(number){
        ^
        exit status 1
        redefinition of ‘bool SendToServer’

        thanks already

        • Michael James on August 12, 2022 at 2:05 pm

          Looks like SendToServer is already defined somewhere? If you post you entire program, it may help track down the issue.

          • René Janssen on August 12, 2022 at 4:03 pm

            here’s the program

            #include
            #include
            #include
            #include

            //===Change values from here===
            const char* ssid = “ssid”;
            const char* password = “password”;
            const char* hostName = “ESPP1Meter”;
            const char* serverIP = “ipadres”;
            const bool outputOnSerial = true;
            //===Change values to here===
            const unsigned int MAX_MESSAGE_LENGTH = 400;

            void setup() {
            delay(1000);
            Serial.begin(115200);
            WiFi.mode(WIFI_OFF);
            delay(1000);
            WiFi.mode(WIFI_STA);
            WiFi.begin(ssid, password);
            Serial.println(“”);
            Serial.print(“Connecting”);
            // Wait for connection
            while (WiFi.status() != WL_CONNECTED) {
            delay(500);
            Serial.print(“.”);
            }
            }

            void loop () {
            CheckTelegram();
            }
            bool SendToServer(message){
            HTTPClient http;
            char url[255];
            sprintf(url, “http://%s/process.php?data=%s”, serverIP, number);
            Serial.printf(“[HTTP] GET… URL: %s\n”,url);
            http.begin(url); //Specify request destination
            int httpCode = http.GET(); //Send the request
            if (httpCode > 0) {
            Serial.printf(“[HTTP] GET… code: %d\n”, httpCode);
            // file found at server
            if (httpCode == HTTP_CODE_OK) {
            String payload = http.getString();
            }
            }else{
            Serial.printf(“[HTTP] GET… failed, error: %s\n”, http.errorToString(httpCode).c_str());
            }
            http.end(); //Close connection
            delay(60000); //GET Data at every minute
            }
            void CheckTelegram(){
            while (Serial.available() > 0) {
            //Create a place to hold the incoming message
            static char message[MAX_MESSAGE_LENGTH];
            static unsigned int message_pos = 0;

            //Read the next available byte in the serial receive buffer
            char inByte = Serial.read();

            //Message coming in (check not terminating character) and guard for over message size
            if ( inByte != ‘!’ && (message_pos < MAX_MESSAGE_LENGTH – 1) )
            {
            //Add the incoming byte to our message
            message[message_pos] = inByte;
            message_pos++;
            }
            //Full message received…
            else
            {
            //Add null character to string
            message[message_pos] = '\0';

            //Print the message (or do other things)
            Serial.println(message);

            //Or convert to integer and print
            int number = atoi(message);
            Serial.println(number);
            SendToServer(message);
            //Reset for the next message
            message_pos = 0;
            }
            }
            }



          • Michael James on August 21, 2022 at 11:33 am

            Hi René – for some reason, it does seems like the libraries you are included did not show up in the comment. You could try posting them with out the angle brackets, as sometimes angle brackets trigger security issue in comments.

            From what I can gather, maybe the function SendToServer has already been created in one of the libraries? You could change the name of your function to something else, and see if that helps?



  8. Roger on October 13, 2022 at 3:23 pm

    What if we have two messages inputs requiring two arrays. How would the code be different?

    • Michael James on October 13, 2022 at 3:41 pm

      I think basically you would create another char array to hold the other message. You would just need a way to determine when one message starts and another ends (maybe a special character is used to split the messages, and when you see that character, you switch which array is holding the message.

  9. Philippe Simon on November 25, 2022 at 4:51 am

    Hello and many thanks – luckily we can find your article !

    But alas my case is a bit out of scope – receiving serial “int’s” from a “processing” code on a windows PC, using serial.write( char() ); – and causes me some trouble.

    No possible to see any result by a serial.print… since the port is busy, but for test I blink the led instead.

    First, the atoi() function does not work at all
    but I get a result with this:
    ///////////////////////////////////////////////////////
    while (Serial.available() > 0)
    {
    static char message[static char message[MAX_MESSAGE_LENGTH];
    static unsigned int message_pos = 0;
    static int sum = 0;

    char inByte = Serial.read();
    if ( inByte != ‘\n’ && (message_pos < 12 – 1) )
    {
    message[message_pos] = inByte;
    message_pos++;
    sum += inByte;
    //sum += inByte*pow(10, message_pos-1); // does not work !!??
    }

    else if ( inByte == '\n') {
    for (int f=0; f<sum; f++)
    {
    delay(30); digitalWrite(13, HIGH);
    delay(30); digitalWrite(13, LOW);
    }
    sum = 0;
    }
    /////////////////////////////////////////////
    It works… with a TENNSY… BUT NOT AN ARDUINO !
    on Arduino (nano & mega):
    1) the card "blink" twice before working, so you have to put a delay of one second before collecting the first char !
    – it is a limite to char(128) (teensy accepts char(255)… better to fill a first shifting byte)

    I have a solution to move forward, that's almost all good. Nevertheless it's strange, incomprehensible to me but you may have an experience ?

    Anyway, many thanks for your article

  10. Philippe Simon on November 25, 2022 at 12:02 pm

    … my first post and in validation, I would like to add a point:

    if ( inByte != ‘!’ && (message_pos …)

    means, unless I’m mistaken (but that’s what happens to me!) that if you have to pass “10”… you exit by the final “else” !

  11. Anton on February 5, 2023 at 6:05 am

    Gonna make myself a ub sandwich, haha. Thanks for your effort, very intuitive video !

  12. mohamed hassine elhani on March 2, 2023 at 9:19 pm

    Hello, i need your help i have a line follower robot and im using an arduino uno for the sensors and the motors but since the pins arent enough im using an esp8266 nodemcu for an ultrasonic senor i can send the measured distance from the esp to the arduino but i cant use it in the program i did the exact steps and when i implement the measured distance as an int in the program its says that it was not declared (i declared it as number like your program)

    • Michael James on March 6, 2023 at 10:50 am

      Hi Mohamed, can you post your code? It may be an issue as to where you are declaring your variables. Also, you have an esp8266 connected to an Arduino UNO, do I understand that correct?

  13. rob nieuwland on October 30, 2023 at 11:26 pm

    Is it required to declare char message at every start of the while loop?
    //Create a place to hold the incoming message
    static char message[MAX_MESSAGE_LENGTH];

    • Michael James on October 31, 2023 at 9:06 am

      Great question Rob! Lots of ways to do this.

      You could make the message array a global variable (outside of setup and loop, in which case you would not need it at the beginning of the loop)

      In this case, with the message array being static, it is only instantiated once, and then skipped over every loop after.

Leave a Comment