Categories
Arduino Examples

How to Read N Number of Bytes from Serial Port in Arduino?

In this post we are going to demonstrate how to read “N” number of bytes from Serial port in Arduino. This is very common problem where we are only focusing on specific number of bytes which are being transmitted from different sensor or even from different microcontroller board. For example in my current case I am sending the 5 bytes from Arduino UNO to ESP8266 NodeMCU. I have to read the 5 bytes through serial port in NodeMCU.

To solve this problem, I have to write a code which could read a complete string until the line break. Or any Specific terminator character using the built-in readStringUntill function. Although, I am sending the starting and trailing characters from Arduino UNO to NodeMCU to differentiate the starting and ending point of data being transmitted. But this post is not about that. Rather I am focusing on how to read exactly n number of bytes. So for that purpose, What I have to do is to wait for that specific bytes to be available in serial port which we can simply poll with Serial.available() function.

Read Bytes in Arduino Serial

Let’s write down a quick code to read N number of bytes from serial port and because we are sending the ‘[‘ for frist character and ‘]’ for last character and exactly 5 bytes including the starting and ending bracket, we can easily validate after receiving the bytes. Once we are done receiving bytes we can make a quick check for starting and ending character and validate if received bytes are valid or invalid.

Here is the code for quick peek

char inputSequence[6]; // Buffer to store the input sequence (5 characters + null terminator)

void setup() {
  Serial.begin(115200); //change this baud rate according to your need
}

void loop() {
  if (Serial.available() >= 5) {
    // Read 5 characters from the Serial port
    Serial.readBytes(inputSequence, 5);
    inputSequence[5] = '\0'; // we need to null terminate it 

    // Print the received sequence
    Serial.print("Received: ");
    
    Serial.println(inputSequence);
    if(inputSequence[0]=='[' && inputSequence[4]==']'){
      Serial.println("Valid");
    }else{
      Serial.println("invalid");
    }
    // Perform actions based on the received inputSequence
   
  }
}

Code language: C++ (cpp)

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.