MEGA 2560, receiving large data from serial port

Hi
I have a problem with receiving large data from serial port on Arduino MEGA 2560.
I need to read about 7000 bytes via serial port from electric meter and send them to server
using GPRS SIM800 module.
I coundn't create so big buffer to read all data in one time and after that send them to server.
I try to read data from Serial2 to a little buffer, if buffer is full send data to server and continues read data from Serial2. But when data come's to server I have a lot of miss bytes.
I made a lot of tests and found the problem. When my buffer is full I try to send data to server and when data is sending in SendData() functions Serial2.read() does not read bytes from serial buffer.
It's mean that incoming data overwrite old data in uart buffer because Serial2.read() is not called when SendData() is wokring. I call WriteDataToSerial3_TCP_CLIENT(5) function in serialEvent2().

How to fix my problem?
May be there is other way to send data via gprs module and read from serial in non blocking way?

#define BUF_SIZE_OUT 64
byte out_bufer[BUF_SIZE_OUT];
void WriteDataToSerial3_TCP_CLIENT(int timeout_byte){
 index_out_buffer = 0;
 memset(out_bufer, '\0', BUF_SIZE_OUT);
 unsigned long start_time = millis();
 do{
 while (Serial2.available() > 0)
 {
 if (index_out_buffer < BUF_SIZE_OUT)
 {
 out_bufer[index_out_buffer] = Serial2.read();
 index_out_buffer++; 
 start_time = millis();
 }
 else
 {
 //Serial.println(F("out_bufer is FULL"));
 SendData(out_bufer, index_out_buffer);
 index_out_buffer = 0;
 memset(out_bufer, '\0', BUF_SIZE_OUT);
 start_time = millis();
 }
 } 
 } while((millis() - start_time) < (unsigned long)timeout_byte);
 SendData(out_bufer, index_out_buffer); 
}
void SendData(byte const *data, int data_size)
{
 
 char at_str[20] = "AT+CIPSEND=";
 char str[5];
 sprintf(str, "%d", data_size);
 strcat(at_str, str); 
 if (SendAtCommands(at_str, "ERROR", 5, 1) == false)
 {
 Serial3.write(data, data_size);
 WaitResp("ACCEPT", 10, 200);
 } 
}

you can lower the baud rate of the incoming data or increase the baud rate of the outgoing data or both.
also use buffered read instead of reading one character at a time.

serial driver will continue to overwrite old data if you do not read it fast enough and it fills up the serial buffer. So the idea is to read and process it faster than it arrives.

as a last resort, if the sender supports hardware handshake, you can use arduino platforms (such as teensy 3.2) that supports hardware handshake to pause incoming data while you process received data.

Baud rate of serial ports:
Serial2 - 9600 - is port for incoming data and I coundn't change it
Serial3 - this port for SIM800 module, I try different speed from 9600 to 115200.
But speed of sending data by SIM800 module depend only from signal strengh.
I also try to use AT+CIPQSEND=1. This command set quick send mode.
If I send data to serial of SIM800 module, it only accept my bytes to his buffer
and send them later.
I will try to use buffered read but don't understand how it can help me?
serialEvent2 it interrupt event or it called each time in loop?

How often do these 7000 byte packets arrive? Is it one right after the other, or do you get a break in between them? If there is a long enough break, you might want to consider a SD card module. Read the serial onto the SD card, then when complete, transfer to the GPRS module.

edit: Does the meter have any hardware or software flow control available? It may be possible to pause the transmit while you send.

I have receive some query from server via GPRS module. When I receive one, I send it to meter.
Then I wait data from meter and if something come from it I must them to server via GPRS module.
All incoming data from server is small packets, max 100bytes.
Outgoing data from meter can be different from 100 to 10kbytes.
For example
in AF 3F B4 39 30 B1 35 B2 B1 21 8D 0A
out AF C5 4D 48 35 5C C0 5C B2 30 B1 CC 5A D1 CA CC 30 30 B1 36 C6 8D 0A
in 81 D2 35 82 50 2E 30 B1 28 B2 B1 36 30 B4 B1 30 B2 B1 30 30 BB B2 B1....
out (packet 7kbytes)
in 81 D2 35 82 50 2E 30 B1 28 B2 B1 36 30 B4 B1 B1 B2 B1 30 30 BB B2 B1 .......
out (packet 7kbytes)

Meter is not my device and I coundn't change it configuration.
And meter have RS485 port

It may not need a configuration change. It may have flow control already there.
http://www.moxa.com/resource_file/509820091121333.pdf
If you can get a make and model off the meter, the meter's user manual or datasheet may have that information available.

That is ASCII readable hexadecimal code with a space in between ?
Could you store it as binary data ?
"AF " is three bytes, but stored as 0xAF takes one byte. You need 3333 bytes to store 10kbyte of incoming characters.
The Arduino Mega 2560 has 8kbyte sram.

Or use code / library for a ring buffer. But that ring buffer could overflow as well. A fixed array of 3333 bytes is safer.

Is about 10kbyte the maximum amount ? Are you sure ?

You have to do both encode and decode of course. When the data is transmitted, it must be converted back to "AF " and so on. It will slow things down, but at 9600 baud it is no problem.

Perhaps you need to use a Arduino with ARM Cortex processor.

Use a chip with more SRAM. '1284P has 16K of SRAM, enough for two 7000 byte buffers.
I offer boards in several form factors, DIP and SMD. One example:
http://www.crossroadsfencing.com/BobuinoRev17

SurferTim:
It may not need a configuration change. It may have flow control already there.
http://www.moxa.com/resource_file/509820091121333.pdf
If you can get a make and model off the meter, the meter's user manual or datasheet may have that information available.

For test I use Converter RS232-RS485 Moxa A52, but can be another convertor.
Meters can be different too. For test I use itron (Actaris) SL7000 and EMH lzqj-xc.
SL7000 use binnary portocol - dlms.
LZQJ use text protocol - IEC1107.
I don't know what meters will be connected to my device.

Binary, you mean that the data is not readable ASCII with a space between them, but binary data, like 0xAF ? The data over RS-232 is often readable ASCII.

I send data to server via stantard tcp socket. Server can be different program and I cound make any changes in data is sending. I want to make device that help to read data from a lot of meters via gprs.
As I understand my problem is that MEGA 2560 have hardware buffer only with 2bytes.

When I test with binary protocol, all is work good.
But when I start to read meter with text protocol, somethings is wrong.
I coundn't understand why I have problem with buffer when work with second meter.
I attach 2 files with logs.
In

EMH.txt (11.8 KB)

SL7_log.txt (15.1 KB)

Last I checked the Mega 2560 has a 64 byte software buffer also, but that is not really your problem. Have you considered migrating your code to a Due? I think 96K of SRAM would solve your problem.

Yes, MEGA 2560 have 64kbytes of software buffer.
Is mean that serial class is reading bytes from hardware bufer to software.
Software buffer sizes are in HardwareSerial.h and I already try to increase buffer to 128 and 256kbytes.
But have no good rezult because I have overwrite bytes in hardware buffer.

I will think about Due but my problem is speed of reading serial buffer.
More RAM can help only if I want to read all data to buffer and then send them to server.

1) Indent your code:

#define BUF_SIZE_OUT 64
byte out_bufer[BUF_SIZE_OUT];

void WriteDataToSerial3_TCP_CLIENT(int timeout_byte)
{
  index_out_buffer = 0;
  memset(out_bufer, '\0', BUF_SIZE_OUT);
  unsigned long start_time = millis();

  do{
    while (Serial2.available() > 0){
      if (index_out_buffer < BUF_SIZE_OUT){
        out_bufer[index_out_buffer] = Serial2.read();
        index_out_buffer++; 
        start_time = millis();
      } else {
        //Serial.println(F("out_bufer is FULL"));
        SendData(out_bufer, index_out_buffer);
        index_out_buffer = 0;
        memset(out_bufer, '\0', BUF_SIZE_OUT);
        start_time = millis();
      }
    } 
  } while((millis() - start_time) < (unsigned long)timeout_byte);

  SendData(out_bufer, index_out_buffer); 
}

void SendData(byte const *data, int data_size)
{
  char at_str[20] = "AT+CIPSEND=";
  char str[5];
  sprintf(str, "%d", data_size);
  strcat(at_str, str); 
  if (SendAtCommands(at_str, "ERROR", 5, 1) == false){
    Serial3.write(data, data_size);
    WaitResp("ACCEPT", 10, 200);
  } 
}

Space characters are free; use them to make your code easy-to-read. If nothing else, hit ctrl-T in the IDE editor too auto-format your code. -_-

2) Did you know that "int timeout_byte" is actually two bytes?

3) Why don't you always send a 64-byte buffer? Pad shorter packets with bytes you can ignore at the receiver. Then you can write the characters as you receive them, and there won't be a big pause in reading while you send.

4) serialEvent is not called from the interrupt. It is equivalent to calling available/read from loop. Even if your function were called from the interrupt, you're just buffering the data. You might as well just increase the 64-byte rx_buffer in the HardwareSerial.* files. Also, you can't do a send from inside an interrupt function. And what does this mean:

But have no good result because I have overwrite bytes in hardware buffer.

5) Your program structure should probably get turned inside-out. Look at Serial Input Basics for how you should be reading constantly and, when a newline comes in, do something. loop gets called many times before it finally does something. That lets other things have a chance to run. Right now, you're staying inside a while loop until you're done reading. Nothing else can happen, which is why you have a "timeout". That's ok on a PC with a nice multi-tasking OS, but that's not ok on the Arduino. Useful Links has lots of good info, not just "Serial Input Basics".

6) Post or attach your entire sketch, but not the libraries... just insert a link for those. You really have a program structure problem, and we can't make a suggestion without seeing the entire program. Snippets (small code excerpts) force us to answer "Y?", when the problem is really "X!" Read this.

Cheers,
/dev

"Yes, MEGA 2560 have 64kbytes of software buffer."

64 kbytes? Seems to be a little on the high side, when there is only 8 kbytes of SRAM.

Maybe 64 bytes.

/dev:
Space characters are free; use them to make your code easy-to-read. If nothing else, hit ctrl-T in the IDE editor too auto-format your code. -_-

Thanks, attach new code

/dev:
2) Did you know that "int timeout_byte" is actually two bytes?

It's time to wait next byte.

/dev:
3) Why don't you always send a 64-byte buffer? Pad shorter packets with bytes you can ignore at the receiver. Then you can write the characters as you receive them, and there won't be a big pause in reading while you send.

I don't know how many bytes I will received from meter. I send buffer when is full.

/dev:
4) serialEvent is not called from the interrupt. It is equivalent to calling available/read from loop. Even if your function were called from the interrupt, you're just buffering the data. You might as well just increase the 64-byte rx_buffer in the HardwareSerial.* files. Also, you can't do a send from inside an interrupt function. And what does this mean:
But have no good result because I have overwrite bytes in hardware buffer.

I already increase buffer to 128bytes. Is mean that I have missed bytes.
I must recieve line in such format - 0.1.2*82(01511240000000)
but sometimes I got 92(00694.295kWh) or 0.9.1(1170555)

/dev:
5) Your program structure should probably get turned inside-out. Look at Serial Input Basics for how you should be reading constantly and, when a newline comes in, do something. loop gets called many times before it finally does something. That lets other things have a chance to run. Right now, you're staying inside a while loop until you're done reading. Nothing else can happen, which is why you have a "timeout". That's ok on a PC with a nice multi-tasking OS, but that's not ok on the Arduino. Useful Links has lots of good info, not just "Serial Input Basics".

6) Post or attach your entire sketch, but not the libraries... just insert a link for those. You really have a program structure problem, and we can't make a suggestion without seeing the entire program. Snippets (small code excerpts) force us to answer "Y?", when the problem is really "X!" Read this.

Cheers,
/dev

I attach my sketch. I understand that I have structure problem but couldn't find it.

GPRS.ino (14 KB)

I attach my sketch.

o_O Did you write all of this, or is it modified from some project?

I understand that I have structure problem but couldn't find it.

Please read Serial Input Basics, especially "Example 2 - - Receive with an end-marker".

The main problem is that you have a very linear, top-to-bottom program structure. Delays are very bad when you have so many things to process. A delay in one part of the program will prevent the serialEvent routines from being called, and you will lose data.

BTW, printing too much debug information on Serial is like a delay: when 64 bytes of debug prints have been queued up, the Serial.print will block until the rest of the print can be queued up. Ack. It takes 86us to print one character to the Serial Monitor window (via Serial) or to Serial3. It takes 1041us (1ms!) to write one character to Serial2. The Arduino can execute 100's to 1000's of instructions during each character time.

In general, you need to let the Arduino keep running, without delays. Then it can check all the serial ports for data (via serialEvent routines). The structure of loop needs to be more like example 2. That example is really a small Finite-state Machine, or FSM. Here's a great description.

Although some parts of your application are sequential, many parts should be implemented and coordinated by a FSM. Your program is too complicated for the simple linear approach.

First, make sure you understand Example 2. Then see if you can apply that technique to some of your routines. The goal is to eliminate delay. (The delays in setup are ok.) You should end up with a routine that gets called repetitively (no delays inside) instead of just once (with a timeout or delay). Most times, no serial data will be available, and it just returns.

I haven't figured out the entire program, but it looks like you may have several states like IDLE, SENDING_BYTES, and WAITING_FOR_REPLY. There may separate states for DISCONNECTED, CONNECTING, and CONNECTED.

I don't know how many bytes I will received from meter. I send buffer when is full.

Yes, I saw that you have to send the "length" first, then the buffer. Won't most packets contain the full 64 bytes? That is, all but the last packet will be 64 bytes?

So why not always write a length of 64, and if the packet doesn't really have 64 bytes, just send spaces or zeroes for the rest. That lets you write the length immediately (64), then write each byte as it is received. You won't have to save bytes, then write length, then write the bytes.

Writing all the bytes at once may block the program at that point... it's like a delay (it depends on what else has been written). If you write one byte when you receive one byte, the output stream will not be "lagging" the input stream. But the last packet could have padding spaces at the end. Can the receiver strip those padding bytes?

Other questions that come to mind:

* Is the energy monitor sending a binary stream or a text stream?

* Is there anything else from the energy monitor that would tell you how many bytes are coming?

* Could you parse the energy monitor data? Then you could send something shorter (a header + a few ints) or fixed-length. Maybe you could do one send every 4 seconds: (16 bytes of binary data) x 4, in one 64-byte packet?

Cheers,
/dev

/dev:
o_O Did you write all of this, or is it modified from some project?

I wrote all lines in this project

/dev:
Please read Serial Input Basics, especially "Example 2 - - Receive with an end-marker".

The main problem is that you have a very linear, top-to-bottom program structure. Delays are very bad when you have so many things to process. A delay in one part of the program will prevent the serialEvent routines from being called, and you will lose data.

BTW, printing too much debug information on Serial is like a delay: when 64 bytes of debug prints have been queued up, the Serial.print will block until the rest of the print can be queued up. Ack. It takes 86us to print one character to the Serial Monitor window (via Serial) or to Serial3. It takes 1041us (1ms!) to write one character to Serial2. The Arduino can execute 100's to 1000's of instructions during each character time.

In general, you need to let the Arduino keep running, without delays. Then it can check all the serial ports for data (via serialEvent routines). The structure of loop needs to be more like example 2. That example is really a small Finite-state Machine, or FSM. Here's a great description.

Although some parts of your application are sequential, many parts should be implemented and coordinated by a FSM. Your program is too complicated for the simple linear approach.

First, make sure you understand Example 2. Then see if you can apply that technique to some of your routines. The goal is to eliminate delay. (The delays in setup are ok.) You should end up with a routine that gets called repetitively (no delays inside) instead of just once (with a timeout or delay). Most times, no serial data will be available, and it just returns.

I haven't figured out the entire program, but it looks like you may have several states like IDLE, SENDING_BYTES, and WAITING_FOR_REPLY. There may separate states for DISCONNECTED, CONNECTING, and CONNECTED.
Yes, I saw that you have to send the "length" first, then the buffer. Won't most packets contain the full 64 bytes? That is, all but the last packet will be 64 bytes?

So why not always write a length of 64, and if the packet doesn't really have 64 bytes, just send spaces or zeroes for the rest. That lets you write the length immediately (64), then write each byte as it is received. You won't have to save bytes, then write length, then write the bytes.

Writing all the bytes at once may block the program at that point... it's like a delay (it depends on what else has been written). If you write one byte when you receive one byte, the output stream will not be "lagging" the input stream. But the last packet could have padding spaces at the end. Can the receiver strip those padding bytes?

I will try to remove all delay from code in Loop. I haven't source code of server side and couldn't change anything. I couldn't send any other byte or "padding spaces". I have different devices that are connected to my arduino. They have different protocols. And there are a lot of queries to meter and answer can be any size. For example, first from server I have AF 3F B4 39 30 B1 35 B2 B1 21 8D 0A and from meter I will get AF C5 4D 48 35 5C C0 5C B2 30 B1 CC 5A D1 CA CC 30 30 B1 36 C6 8D 0A. I don't how many bytes come from meter.

/dev:
Other questions that come to mind:
* Is the energy monitor sending a binary stream or a text stream?

I have to main meters SL7000 and EMH LZQJ. SL7000 it - binary stream with protocol dlms. Max size of packet is about 150bytes. EMH LZQJ - text stream and max sizes of one packet for this meter can be about 7000 bytes.

/dev:
* Is there anything else from the energy monitor that would tell you how many bytes are coming?

I have console on server side where I can see how many bytes are send and recieved by server.

/dev:
* Could you parse the energy monitor data? Then you could send something shorter (a header + a few ints) or fixed-length. Maybe you could do one send every 4 seconds: (16 bytes of binary data) x 4, in one 64-byte packet?

Cheers,
/dev

I already think about how to send data with const length but coundn't know how to get it.
I read your Serial Input Basics Example 2 but counldn't understand how to use it for my sketch.
I have different portocols with different query length and don't know what byte I can use as endMarker.
I will try to send data when recieved 16bytes.

I also make little sketch for test without GPRS module. I modify DataSend function.

void SendData(byte const *data, int data_size) {
  for (int i = 0; i < data_size; i++) Serial.write(data[i]);
  delay(10); // for emulate sending data via GPRS modem
}

If I set delay(1) all bytes ara recieved from meter.
If I set delay(10) I have overwrite bytes.
I think that I need to send data not from WriteDataToSerial3_TCP_CLIENT function,
I must make it from loop and to make send data no blocking function.

MultiSerial.ino (2.04 KB)

I haven't source code of server side and couldn't change anything... And there are a lot of queries to meter and answer can be any size.

Ok, you will have to buffer it like you are doing now. 64 bytes isn't a huge buffer, I just wondered if there was some way to eliminate it.

I read your Serial Input Basics Example 2 but couldn't understand how to use it for my sketch... and don't know what byte I can use as endMarker.

The "end marker" for you is the timeout. It's an end "condition", not a character like '\n'.

Right now your sketch watches for the first character to appear on Serial, and then it waits for the whole packet to come in. If no more characters have arrived after 50ms, it assumes the packet has been completely received:

void loop()
{
  // read from port 1, send to port 0:
  if (Serial.available()) 
  {
    ReadDataFromSerial3_buf(50);
    WriteDataToSerial2();
  }

I'd like to suggest moving all these statements into ReadDataFromSerial3_buf, or Read3 for short:

void loop()
{
  // read from port 1, send to port 0:
  Read3( 50 );
     .
     .
     .
}

void Read3( int timeout_max )
{
  if (Serial.available()) {

    index_in_buffer = 0;
    memset(in_bufer, '\0', BUF_SIZE_IN);
    unsigned long start_time = millis();

    do {
       .
       .
       .
    } while((millis() - start_time) < (unsigned long)timeout_max);
  
    WriteDataToSerial2();
  }
}

The real problem is that you are blocked inside this routine until all data has been received, plus 50ms. Too long! Serial Input Basics shows how to not block while waiting for a '\n'. To paraphrase that example:

int     index = 0;
uint8_t buffer[ 64 ];

void loop()
{
  while (Serial.available()) {
    uint8_t c = Serial.read();

    if (c == '\n') {
      // End of line!
      buffer[ index ] = 0; // NUL-terminate the array so we can...
      Serial.println( buffer ); // ...write it out as a C string (Serial.write does not need NUL)
      index = 0; // ...and start saving a new line.

    } else {
       // Save another char, if there is room
       if (index < sizeof(buffer)-1) {
         buffer[ index++ ] = c;
       }
    }
  }
}

Notice how it does not stay in the while loop until the '\n' is received. It just saves whatever characters are available now, and then exits the while loop. Most of the time, Serial.avaiable() will be zero. No big deal, it just skips the while loop. When a character is finally available (once every 1000 calls!), it reads the character and either (1) saves it, or (2) prints out the whole buffer (and resets the index).

The Arduino is free to process everything else while the buffer is being accumulated from individual characters. Let's change that to an end condition, when no characters have been received for 50ms:

uint32_t lastRX;

void loop()
{
  while (Serial.available()) {
    uint8_t c = Serial.read();

    // Save another char, if there is room
    if (index < sizeof(buffer)-1) {
      buffer[ index++ ] = c;
    }

    // Remember that we just got a character
    lastRX = millis();
  }
  
  if ((index > 0) && (millis() - lastRX > 50)) {
    // We have some chars, and it has been 50ms since the last char was received.

    buffer[ index ] = 0; // NUL-terminate the string so we can...
    Serial.println( buffer ); // ...write it out as a C string (Serial.write does not need NUL)
    index = 0; // ...and start saving a new line.
  }
}

Notice how this accumulates chars if they are available, sets the time stamp, and then moves on. If no chars are available, lastRX does not get updated. When no chars have been available for 50ms, it prints the chars that have been accumulated. No blocking, no delays.

To apply this to your program, you should restructure Read3 to do the same thing. Accumulate the characters that are available "now". Then test if it has been 50ms since the last character. If it has, forward the entire buffer to Serial2 and reset the index.

void Read3( int timeout_max )
{
  static int      index = 0;
  static uint32_t lastRX; // time stamp

  while (Serial.available()) {
    uint8_t c = Serial.read();
    in_bufer[ index++ ] = c;
    if (index >= BUF_SIZE_IN)
      break;       
    lastRX = millis();
  }
  
  // Send the buffer if it is full  OR  it's time to send what we have
  if ((index >= BUF_SIZE_IN) ||
      ((index > 0) && ((millis() - lastRX) < (unsigned long)timeout_max))) {
    WriteDataToSerial2();
    index = 0;
  }
}

Notice how the while loop is terminated if the buffer is full. The next if statement will write the full buffer, OR write a partial buffer if it has been 50ms.

Apply this same technique to all inputs.

Cheers,
/dev