UART recieve question

Could anybody help me please with the problem of uart data recieve at arduino nano.

The problem is - I’ve connect GPS (for example) that send GPGGA data to soft serial of arduino nano every 1 second,
then I try to find the end of the string of gps data (search for “CR”) and place it to char array.
And finnaly print it to serial monitor.
But I place a delay for 7 second between every print to monitor.
So if there is a delay between of them I recieve at serial monitor sometimes two sticked GPGGA strings.
Could anybody please help me to understand why is it happend?

My code is (I simplified my code for this example.):

#include <SoftwareSerial.h> 
#define RXD 2
#define TXD 3

SoftwareSerial soft_serial(RXD, TXD);
unsigned char serial_buffer[100];

void setup(){

void loop(){
 if (Read_UART(, serial_buffer, 100) >0) {  

int Read_UART(int source, unsigned char *buffer, unsigned int len)
  static unsigned int pos = 0;
  unsigned int rpos;
  if (source > 0) {
    switch (source) {
      case '\n':
      case '\r':
        rpos = pos;
        pos = 0; 
        return rpos;
         if (pos < len-1) {
         buffer[pos++] = source;
         buffer[pos] = 0;
  return -1;

Why not use

if (soft_serial.available())

to determine whether there is data ready to be read and if there is, read a byte until you get the CR ?

I use

if ( >0)

in Read_UART()

But anyway I just tried to use instead:

if (source >0)

"available" variant:

if (soft_serial.available()) {

And I get the same problem...

Ok. Everything works fine if I place .end and .begin for clean uart buffer:


and another way for clean uart buffer


Based on your code, you expect the end of the line to consist of "\r\n". Is that indeed the case? What if it's only "\n"? You will never reset 'pos' and hence keep adding data to buffer till it overflows.

Just check if you indeed receive a '\r'.

And a simple solution might be to remove the break; in the case '\n': so it will fall through to the case '\r': and reset 'pos'.