If I send a long string to arduino by serial communication, how many characters can the buffer hold?

I want to send a long string via serial communication to arduino, let's say 200 characters. I know arduino buffer can only hold 64 bytes, so does that mean I can only store 64 characters? What can I do if I don't want to lose the rest of them? Thanks!

Read them as they arrive. The processor is fast compared to the Serial baud rate.
See this tutorial which explains
https://forum.arduino.cc/t/serial-input-basics-updated/382007

Serial by definition, sends data serially... one byte after another. You should read them the same way... you don't wait for them all to arrive.

So general flow...

loop
{
  read some bytes into my array (processor can read them way faster than they can be sent)

  if I have everything I need (e.g. end byte received, or x bytes read)
  {
    process my array
    clear my array
  }

  do other stuff
}

Usually you would read them into an array. Once you have received the data you want then process it.

There are very many ways to process on a character-by-character basis. I often use something like this:


  if (Serial1.available())
  {
    char c = Serial1.read() ;
    if (c)                            // non-Null character
    {
      // if ( c == 10 ) c = 13 ;      // translate LF to CR and implement as CR+LF
      if( c > 31 && c < 127)          // keep non-printables off LCD
      {
        if ( c == cWatchChar )
        {
          lcd.setTextColor(ILI9340_RED, ILI9340_BLACK) ;
          lcd.print(c) ;
          lcd.setTextColor(ILI9340_GREEN, ILI9340_BLACK) ;
        } else {
        lcd.print(c) ;
        }
        ++nLCD ;                      // increment character count
      }

      switch (c)  {                   // Operate upon a few control characters

..... and so on ....

Be sure to look inti using <Streaming.h>
http://arduiniana.org/libraries/streaming/

Full source code:
https://forum.arduino.cc/t/the-qbf-the-quick-brown-fox-for-serial-diags/229468

You can reliably transfer 254 bytes of data at a time between Arduinos easily using SerialTransfer.h. It's installable via the Arduino IDE's Libraries Manager and comes with examples.

You can study Serial Input Basics - updated to get an understanding.

On some non-Arduino cores (STM32duino for example) the core function is made weak so that it can be overwritten with a non-default value.

and where do I save them? because let's say depending on the character I have to call a different function

Did you read the recommended tutorial?

You can store the received bytes in something like

char myLongReceivedMessage[200]

I send a txt file data and my code that I took from that "Serial Input Basics" just reads until the second txt file line. Then it restarts from the 1rst line. Any idea how can I fix the problem so it reads all the lines?

Please:

  1. Show your code in a reply.
  2. Attach (a small example of) the text file to a reply. Attaching is preferred so we can check the line endings.
  3. What do you use to send the text file?

These sketches transfer a text file over UART:

TX:

#include "SerialTransfer.h"


SerialTransfer myTransfer;

const int fileSize = 2000;
char file[fileSize] = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc, quis gravida magna mi a libero. Fusce vulputate eleifend sapien. Vestibulum purus quam, scelerisque ut, mollis sed, nonummy id, metus. Nullam accumsan lorem in dui. Cras ultricies mi eu turpis hendrerit fringilla. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; In ac dui quis mi consectetuer lacinia. Nam pretium turpis et arcu. Duis arcu tortor, suscipit eget, imperdiet nec, imperdiet iaculis, ipsum. Sed aliquam ultrices mauris. Integer ante arcu, accumsan a, consectetuer eget, posuere ut, mauris. Praesent adipiscing. Phasellus ullamcorper ipsum rutrum nunc. Nunc nonummy metus. Vestib";
char fileName[] = "test.txt";


void setup()
{
  Serial.begin(115200);
  Serial1.begin(115200);
  
  myTransfer.begin(Serial1);
}


void loop()
{
  myTransfer.sendDatum(fileName); // Send filename
  
  uint16_t numPackets = fileSize / (MAX_PACKET_SIZE - 2); // Reserve one byte for current file index
  
  if (fileSize % MAX_PACKET_SIZE) // Add an extra transmission if needed
    numPackets++;
  
  for (uint16_t i=0; i<numPackets; i++) // Send all data within the file across multiple packets
  {
    uint16_t fileIndex = i * MAX_PACKET_SIZE; // Determine the current file index
    uint8_t dataLen = MAX_PACKET_SIZE - 2;

    if ((fileIndex + (MAX_PACKET_SIZE - 2)) > fileSize) // Determine data length for the last packet if file length is not an exact multiple of MAX_PACKET_SIZE-2
      dataLen = fileSize - fileIndex;
    
    uint8_t sendSize = myTransfer.txObj(fileIndex); // Stuff the current file index
    sendSize = myTransfer.txObj(file[fileIndex], sendSize, dataLen); // Stuff the current file data
    
    myTransfer.sendData(sendSize, 1); // Send the current file index and data
    delay(100);
  }
  delay(10000);
}

RX:

#include "SerialTransfer.h"


SerialTransfer myTransfer;

const int fileSize = 2000;
char file[fileSize];
char fileName[10];


void setup()
{
  Serial.begin(115200);
  Serial1.begin(115200);
  
  myTransfer.begin(Serial1);
}


void loop()
{
  if (myTransfer.available())
  {
    if (!myTransfer.currentPacketID())
    {
      myTransfer.rxObj(fileName);
      Serial.println();
      Serial.println(fileName);
    }
    else if (myTransfer.currentPacketID() == 1)
      for(uint8_t i=2; i<myTransfer.bytesRead; i++)
        Serial.print((char)myTransfer.packet.rxBuff[i]);
    Serial.println();
  }
}

Yep, I already read the serial input basics.
But if I want to save let's say 300? then I can no longer use byte and If I switch to int, there's a problem

The question is - why would you want to store them and not use them?

So don't do it! :wink:

What?

I realise you know this, but bear with me. UART serial communication works in 'packets' of eight bits (i.e. bytes, to all intents and purposes) and each byte is entirely independent of those that went before and come after, and the serial protocol doesn't know or care whether the bits represent an ASCII character, an eight-bit number, part of a 16-bit number, or anything else. If you want to send a 16-bit value, then either you or the library must split it into two bytes, and reassemble at the far end. Importantly, the UART doesn't know or care whether two bytes are actually a 16-bit value, two ASCII characters, or some other data. All it knows about are bytes.

Obviously the maximum numerical value a byte can contain is 255. If you want to send a numerical value of 300, as per your example, then you must send it as two bytes. Alternatively, you can send it as three ASCII characters '3' '0' '0'.

I'd like to suggest you read carefully the reference documentation on Serial.print() and Serial.write(). I think that will answer all your questions. Those library functions look after all the splitting and reassembling for you.

1 Like

your answer isn't useful

thanks for your help!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.