/*
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;
}
}
}