Serial communication isuue

why for input hex values FF FF FF FF 0D BC CB 8E atmega2560 is giving 00 00 00 00 79 48 63 E2 on debug port i am keeping baud rate same only input is at serial 1 and debug serial is at serial 0 this is happening with mega2560 Arduino kit also
my code attached

const int PACKET_SIZE = 139;
uint8_t gpsData[PACKET_SIZE];
//uint8_t byte;
char sentenceRMC[100];
char sentenceGGA[100];
float lastHeadingDeg = 0.0f; // most recent heading to send
uint8_t calcChecksum(const char* s) {
  uint8_t sum = 0;
  for (int i = 1; s[i] != '*' && s[i] != '\0'; i++) {
    sum ^= s[i];
  }
  return sum;
}

void buildNMEASentences() {
  // Simulated extraction from packet
  int hour   = gpsData[0];  // byte 0
  int minute = gpsData[1];  // byte 1
  int second = gpsData[2];  // byte 2

  char ns = gpsData[6];     // byte 6 (e.g., 'N')
  char ew = gpsData[10];    // byte 10 (e.g., 'E')

  float speed = 22.4;       // Dummy values
  float course = 84.4;
  int day   = gpsData[15];
  int month = gpsData[16];
  int year  = gpsData[17];

  // Build RMC
  sprintf(sentenceRMC,
    "$GPRMC,%02d%02d%02d,A,4807.038,%c,01131.000,%c,%.1f,%.1f,%02d%02d%02d",
    hour, minute, second, ns, ew, speed, course, day, month, year);
  uint8_t crcRMC = calcChecksum(sentenceRMC);
  sprintf(sentenceRMC + strlen(sentenceRMC), "*%02X\r\n", crcRMC);

  // Build GGA
  sprintf(sentenceGGA,
    "$GPGGA,%02d%02d%02d,4807.038,%c,01131.000,%c,1,08,0.9,545.4,M,46.9,M,,",
    hour, minute, second, ns, ew);
  uint8_t crcGGA = calcChecksum(sentenceGGA);
  sprintf(sentenceGGA + strlen(sentenceGGA), "*%02X\r\n", crcGGA);
}

void setup() {
  Serial.begin(115200);      // Debug
  Serial1.begin(115200);   // Read 139-byte packet from Serial
  Serial2.begin(115200);   // Output NMEA to USB serial1
  //Serial1.println("Waiting for 139-byte packet...");
}

void loop() {
  static int index = 0;
  uint8_t syncMatch = 0;
  while (Serial1.available() && index < PACKET_SIZE) {
   gpsData[index++] = Serial1.read();
   /*if(2 < index < 4)
   {
    if (gpsData[0] == 0xFF && gpsData[1] == 0xFF &&
        gpsData[2] == 0xFF && gpsData[3] == 0xFF) 
    {}
    else
    {index = 0;}
   } */
    /*if (syncMatch < 4) {
        // Still searching for sync pattern
        if (byte == 0xFF) {
            syncMatch++;
            if (syncMatch == 4) {
                // Sync fully detected → reset buffer & store first byte
                index = 0;
                gpsData[index++] = byte;
                gpsData[index++] = byte;
                gpsData[index++] = byte;
                gpsData[index++] = byte;
                //rxIndex = 3;
            }
        } else {
            syncMatch = 0; // reset if mismatch
        }
    }
   else {
    gpsData[index++] = byte;}//Serial1.read();*/
  }
       Serial.print("Packet: ");
        for (int i = 0; i < PACKET_SIZE; i++) {
        if (gpsData[i] < 0x10) Serial.print("0"); // leading zero
        Serial.print(gpsData[i],HEX);
        Serial.print(" ");
        }
        Serial.println();

    uint32_t b1 = gpsData[46];
    uint32_t b2 = gpsData[47];
    uint32_t b3 = gpsData[48];
    uint32_t headingHex = (b1 << 16) | (b2 << 8) | b3;

    // float heading = headingHex * 0.000021457672119140625;
      lastHeadingDeg = (float)headingHex * 0.000021457672119140625f;    
    char headingStr[12];
    dtostrf(lastHeadingDeg, 0, 3, headingStr); // width=0, precision=3

    char sentence[32];
    snprintf(sentence, sizeof(sentence), "$HEHDT,%s,T", headingStr);

    // Compute XOR checksum over characters after '$' up to before '*'
    uint8_t cs = 0;
    for (size_t i = 1; sentence[i] != '\0'; ++i) cs ^= (uint8_t)sentence[i];

    // Transmit
    Serial2.print(sentence);
    Serial2.print('*');
    if (cs < 16) Serial2.print('0');
    Serial2.print(cs, HEX);
    Serial2.print("\r\n");  
    index = 0;  
  /*if (index == PACKET_SIZE) {
    index = 0;  // Reset for next packet
    buildNMEASentences();

    Serial1.print(sentenceRMC);
    Serial1.print(sentenceGGA);
  }*/
}

I moved your topic to an appropriate forum category @anjana_pathak.

In the future, when creating a topic please take some time to pick the forum category that best suits the subject of your topic. There is an "About the _____ category" topic at the top of each category that explains its purpose.

This is an important part of responsible forum usage, as explained in the "How to get the best out of this forum" guide. The guide contains a lot of other useful information. Please read it.

Thanks in advance for your cooperation.

Are you inputting those bytes from the InputBox (Fig-1) of Serial Monitor and seeing them on the OutputBox of Serial Monitor?


Figure-1:

How are you reading those hex values on Serial? I don't see that code after a quick look.

In the future, please do an Auto Format, it is under the Tools menu.

This

Does not guarantee you’ll read PACKET_SIZE bytes. You’ll empty the incoming buffer faster than the data arrives and so when doing

You are likely printing lots of garbage and reading from garbage

Will result in garbage out

(we say GIGO = Garbage In, Garbage out).

I would suggest to study Serial Input Basics to understand how to correctly handle an asynchronous stream.

I am using dockligth to send hex packet

I user uart isr also to read 139 byte

include <Arduino.h>

#define PACKET_SIZE 139
#define START_PATTERN_LEN 4
const uint8_t startPattern[START_PATTERN_LEN] = {0xFF, 0xFF, 0xFF, 0xFF};

volatile uint8_t packetBuffer[PACKET_SIZE];
volatile uint8_t rxIndex = 0;
volatile bool packetReady = false;
volatile uint8_t syncMatch = 0;
// Timer1 flag
volatile bool sendFlag = false;
volatile float lastHeadingDeg = 0.0f; // most recent heading to send

// Timer1 compare ISR -> sets flag at 10Hz
ISR(TIMER1_COMPA_vect) {
  sendFlag = true;
}
/*ISR(USART1_RX_vect) {
    uint8_t b = UDR1;

    if (!packetReady) {
        if (startMatch < START_PATTERN_LEN) {
            if (b == startPattern[startMatch]) {
                startMatch++;
                if (startMatch == START_PATTERN_LEN) {
                    rxIndex = 0; // start filling packet
                    
                }
            } else {
                startMatch = 0; // restart pattern match
            }
        } else {
            rxBuffer[rxIndex++] = b;
            if (rxIndex >=( (PACKET_SIZE-1) - START_PATTERN_LEN)) {
                packetReady = true;
                startMatch = 0;
            }
        }
    }
    // Store byte
        packetBuffer[rxIndex++] = byte;

        // If full packet received
        if (rxIndex >= (PACKET_SIZE-1)) 
        {
            rxIndex = 0;
            packetReady = true;
        }
}*/

// UART1 receive ISR
/*ISR(USART1_RX_vect) {
    uint8_t byte = UDR1; // Read received byte

    packetBuffer[rxIndex++] = byte;

    if (rxIndex >= PACKET_SIZE) {
        rxIndex = 0;
        packetReady = true;
    }
}*/


ISR(USART1_RX_vect) {
    uint8_t byte = UDR1;  // read received byte

    if (packetReady) {
        return;  // wait until main loop clears it
    }

    if (syncMatch < START_PATTERN_LEN) {
        // Still searching for sync pattern
        if (byte == 0xFF) {
            syncMatch++;
            if (syncMatch == START_PATTERN_LEN) {
                // Sync fully detected → reset buffer & store first byte
                rxIndex = 0;
                packetBuffer[0] = byte;
                packetBuffer[1] = byte;
                packetBuffer[2] = byte;
                packetBuffer[3] = byte;
                rxIndex = 3;
            }
        } else {
            syncMatch = 0; // reset if mismatch
        }
    } 
    else {
        // Already found sync → continue filling packet
        rxIndex++;
        packetBuffer[rxIndex] = byte;
        
        if (rxIndex >= (PACKET_SIZE-1)) {
            // Full packet received
            packetReady = true;
            syncMatch = 0;   // reset sync search for next packet
            rxIndex = 0;     // reset buffer index
        }
    }
}

// Setup Timer1 for 10Hz CTC
void setupTimer1_10Hz() {
  noInterrupts();
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1  = 0;
  OCR1A = 15612; // (16,000,000 / 1024 / 10) - 1 = 1561
  TCCR1B |= (1 << WGM12); // CTC
  TCCR1B |= (1 << CS12) | (1 << CS10); // prescaler 1024
  TIMSK1 |= (1 << OCIE1A); // enable compare A interrupt
  interrupts();
}

void setup() {
    Serial.begin(115200);
    Serial2.begin(4800);

    // Configure UART1 manually for RX interrupt
    UBRR1H = 0;
    UBRR1L = 8; // 115200 baud @ 16 MHz
    UCSR1B = (1 << RXEN1) | (1 << RXCIE1); // Enable RX + RX interrupt
    UCSR1C = (1 << UCSZ11) | (1 << UCSZ10); // 8N1

    setupTimer1_10Hz();
}

void loop() {
    if (packetReady){
    

    // Verify start pattern 0xFF 0xFF 0xFF 0xFF
    if (packetBuffer[0] == 0xFF && packetBuffer[1] == 0xFF &&
        packetBuffer[2] == 0xFF && packetBuffer[3] == 0xFF) 
    {
        // Extract heading from bytes 46, 47, 48
        uint32_t b1 = packetBuffer[46];
        uint32_t b2 = packetBuffer[47];
        uint32_t b3 = packetBuffer[48];
        uint32_t headingHex = (b1 << 16) | (b2 << 8) | b3;

       // float heading = headingHex * 0.000021457672119140625;
          lastHeadingDeg = (float)headingHex * 0.000021457672119140625f;

        // Debug print minimal (avoid heavy prints often)
       /* Serial.print(F("PKT received, headingRaw=0x"));
        Serial.print(headingHex, HEX);
        Serial.print(F(", deg="));
        Serial.println(lastHeadingDeg, 3);*/
        Serial.print("Packet: ");
        for (int i = 0; i < PACKET_SIZE; i++) {
        if (packetBuffer[i] < 0x10) Serial.print("0"); // leading zero
        Serial.print(packetBuffer[i], HEX);
        Serial.print(" ");
        }
        Serial.println();
        packetReady = false;
    }
    }
     if (sendFlag) {
    sendFlag = false;

    // Build NMEA sentence into small buffer (use dtostrf for float -> string if needed)
    // We'll format with 3 decimals
    char headingStr[12];
    dtostrf(lastHeadingDeg, 0, 3, headingStr); // width=0, precision=3

    char sentence[32];
    snprintf(sentence, sizeof(sentence), "$HEHDT,%s,T", headingStr);

    // Compute XOR checksum over characters after '$' up to before '*'
    uint8_t cs = 0;
    for (size_t i = 1; sentence[i] != '\0'; ++i) cs ^= (uint8_t)sentence[i];

    // Transmit
    Serial2.print(sentence);
    Serial2.print('*');
    if (cs < 16) Serial2.print('0');
    Serial2.print(cs, HEX);
    Serial2.print("\r\n");
   // packetReady = false;
    
  }
}

What are the issues with this latest code?

Hi @anjana_pathak ,

there is quite likely no need to use an ISR to read the data ...

Feel free to check this out on Wokwi:

https://wokwi.com/projects/440292263659666433

Sketch:

/*
  Forum: https://forum.arduino.cc/t/serial-communication-isuue/1404030
  Wokwi: https://wokwi.com/projects/440292263659666433

  2025/08/25

  ec2021
*/

const int PACKET_SIZE = 139;
uint8_t gpsDataIn[PACKET_SIZE];
uint8_t gpsDataOut[PACKET_SIZE];
constexpr uint8_t syncLen {4};

void setup() {
  Serial.begin(115200);      // Debug
  Serial1.begin(115200);   // Read 139-byte test packet from Serial3
  Serial3.begin(115200);
  // Preset some dummy data with 0xFF in the first 4 bytes
  for (int i = 0; i < PACKET_SIZE; i++) {
    if (i < 4) {
      gpsDataOut[i] = 0xFF;
    } else {
      gpsDataOut[i] = i;
    }
  }
}


void loop() {
  sendGpsOut();  // Just used to simulate the package transmission, here from Serial3 to Serial1
  if (packetReceived()) {
    printAndEmptyPacket();
  }
}

boolean packetReceived() {
  static uint8_t index = syncLen;
  static uint8_t syncCount = 0;
  while (Serial1.available()) {
    uint8_t c = Serial1.read();
    if (syncCount < syncLen) {
      if (c == 0xFF) {
        gpsDataIn[syncCount] = 0xFF;
        syncCount++;
      } else {
        syncCount = 0;
      }
    } else {
      gpsDataIn[index++] = c;
      if (index >= PACKET_SIZE) {
        index = syncLen;
        syncCount = 0;
        return true;
      }
    }
  }
  return false;
}

void printAndEmptyPacket() {
  Serial.println("*********************************************************");
  Serial.print("Packet received at "); Serial.println(millis());
  for (int i = 0; i < PACKET_SIZE; i++) {
    if (gpsDataIn[i] < 0x10) Serial.print("0"); // leading zero
    Serial.print(gpsDataIn[i], HEX);
    Serial.print(" ");
    gpsDataIn[i] = 0x00;
    if ((i + 1) % 16 == 0) {
      Serial.println();
    }
  }
  Serial.println("\n*********************************************************\n");
}

void sendGpsOut() {
  static unsigned long lastTx = 0;
  static uint8_t idx = 0;
  if (millis() - lastTx > 10) {
    lastTx = millis();
    if (idx == 0) {
      if (random(100) > 50) {
        Serial.print("Start wrong packet at ");
        gpsDataOut[0] = 0x00; // create a wrong packet header
      } else {
        Serial.print("Start new packet at ");
        gpsDataOut[0] = 0xFF;
      }
      Serial.println(millis());
    }
    Serial3.write(gpsDataOut[idx++]);
    if (idx > PACKET_SIZE) {
      idx = 0;
    }
  }
}

One of the most important tools in software development is the use of a test environment for crucial parts of the application.

The sketch above transmits a dummy data packet where the first four bytes are set to 0xFF and the rest is filled up with the index number. So you can directly see if all values have been received correctly or not. After reception and printing the receive buffer is immediately cleared to zero.

Based on a random number the test transmission function sends a "correct" or a "wrong" sync header.

This is the most relevant part:

boolean packetReceived() {
  static uint8_t index = syncLen;
  static uint8_t syncCount = 0;
 // While there is data available in the Serial1 buffer we check them
  while (Serial1.available()) {
    // read the next character from the buffer
    uint8_t c = Serial1.read();
    // If we haven't found enough subsequent sync characters yet
    if (syncCount < syncLen) {
      // We check if this char is a sync char
      if (c == 0xFF) {
        // If yes we store it in the input buffer at the correct space
        gpsDataIn[syncCount] = 0xFF;
       // and increment our sync counter 
        syncCount++;
      } else {
       // If it was no snyc char we start synchronization from zero 
        syncCount = 0;
      }
    } else {
        // But if we have found enough sync characters
      // We start filling the input buffer with data
      gpsDataIn[index++] = c;
     // If our index reaches the PACKET_SIZE
    // we reset index to the space after the last sync character (which is gpsDataIn[syncLen])
    // we reset the sync counter 
    // and we return true as the packet has been received successfully  
      if (index >= PACKET_SIZE) {
        index = syncLen;
        syncCount = 0;
        return true;
      }
    }
  }
  // in all other cases false will be returned
  return false;
}

There may be further issues to check, e.g. a checksum and a timeout.

It should be easy to add this using this kind of test environment before you start to use real gps data ...

Good luck!
ec2021

And to make it more versatile here a version with a start pattern of e.g. eight characters:

/*
  Forum: https://forum.arduino.cc/t/serial-communication-isuue/1404030
  Wokwi: https://wokwi.com/projects/440296681748976641

  previous version  see Wokwi: https://wokwi.com/projects/440292263659666433

  This version has a startPattern of 8 characters

  2025/08/25

  ec2021
*/

const int PACKET_SIZE = 139;
uint8_t gpsDataIn[PACKET_SIZE];
uint8_t gpsDataOut[PACKET_SIZE];
constexpr uint8_t syncLen {8};
constexpr uint8_t startPattern[syncLen] = {0xF0, 0xF1, 0xF2, 0xF3, 0xF3, 0xF2, 0xF1, 0xF0};

void setup() {
  Serial.begin(115200);      // Debug
  Serial1.begin(115200);   // Read 139-byte test packet from Serial3
  Serial3.begin(115200);
  // Preset some dummy data with 0xFF in the first 4 bytes
  for (int i = 0; i < PACKET_SIZE; i++) {
    if (i < 4) {
      gpsDataOut[i] = 0xFF;
    } else {
      gpsDataOut[i] = i;
    }
  }
}


void loop() {
  sendGpsOut();  // Just used to simulate the package transmission, here from Serial3 to Serial1
  if (packetReceived()) {
    printAndEmptyPacket();
  }
}

boolean packetReceived() {
  static uint8_t index = syncLen;
  static uint8_t syncCount = 0;
  while (Serial1.available()) {
    uint8_t c = Serial1.read();
    if (syncCount < syncLen) {
      if (c == startPattern[syncCount]) {
        gpsDataIn[syncCount] = startPattern[syncCount];
        syncCount++;
      } else {
        syncCount = 0;
      }
    } else {
      gpsDataIn[index++] = c;
      if (index >= PACKET_SIZE) {
        index = syncLen;
        syncCount = 0;
        return true;
      }
    }
  }
  return false;
}

void printAndEmptyPacket() {
  Serial.println("*********************************************************");
  Serial.print("Packet received at "); Serial.println(millis());
  for (int i = 0; i < PACKET_SIZE; i++) {
    if (gpsDataIn[i] < 0x10) Serial.print("0"); // leading zero
    Serial.print(gpsDataIn[i], HEX);
    Serial.print(" ");
    gpsDataIn[i] = 0x00;
    if ((i + 1) % 16 == 0) {
      Serial.println();
    }
  }
  Serial.println("\n*********************************************************\n");
}

void sendGpsOut() {
  static unsigned long lastTx = 0;
  static uint8_t idx = 0;
  if (millis() - lastTx > 10) {
    lastTx = millis();
    if (idx == 0) {
      for (int i = 0; i < syncLen; i++) {
        gpsDataOut[i] = startPattern[i];
      }
      if (random(100) > 50) {
        Serial.print("Start wrong packet at ");
        gpsDataOut[0] = gpsDataOut[0]+1; // create a wrong packet header
      } else {
        Serial.print("Start new packet at ");
      }
      Serial.println(millis());
    }
    Serial3.write(gpsDataOut[idx++]);
    if (idx > PACKET_SIZE) {
      idx = 0;
    }
  }
}

To be tested on https://wokwi.com/projects/440296681748976641