🛠 Dialoguer avec un GPS (ou tout module TTL) sur Serial1 sans bloquer la boucle

Arduino Due · intermediaire · Schéma : IMG-due-intermediaire-2-gps-non-bloquant-serial1.svg — module GPS connecté à l'Arduino Due sur Serial1 (RX=18, TX=19, GND, 3,3 V), encart « logique 3,3 V : niveau-baisseur requis pour un module 5 V », trame NMEA affichée.

Objectives

The Due has 4 hardware UARTs: Serial (pins 0/1, connected to the Programming port), Serial1 (USART0, pins 18/19), Serial2 (16/17), and Serial3 (14/15) — not to mention SerialUSB. You will connect a GPS module (or any TTL serial device) to Serial1, which is free from USB usage, and learn asynchronous reading using available/read with NMEA frame parsing, to avoid blocking the loop with readString.

Hardware

Complete Code

// Lecteur de ligne non bloquant sur Serial1 (RX=18, TX=19)
char   ligne[128];
size_t len = 0;
uint32_t dernierOctetMs = 0;

void setup {
  SerialUSB.begin(115200);   // debug sur le port Native
  Serial1.begin(9600);       // typical GPS baud (NEO-6M : 9600)
}

void loop {
  // 1) Vider le FIFO sans jamais bloquer
  while (Serial1.available) {
    char c = (char)Serial1.read;
    dernierOctetMs = millis;
    if (c == '\n' || len == sizeof(ligne) - 1) {   // fin de trame
      ligne[len] = '\0';
      if (len > 6 && strncmp(ligne, "$GNGGA", 6) == 0) {
        SerialUSB.printf("trame GGA (%u octets)\n", (unsigned)len);
      }
      len = 0;
      continue;
    }
    if (c != '\r') ligne[len++] = c;
  }
  // 2) Clôturer une trame orpheline après 100 ms de silence
  if (len && millis - dernierOctetMs > 100) {
    ligne[len] = '\0';
    SerialUSB.printf("flush timeout: %s\n", ligne);
    len = 0;
  }
  // 3) Ici, toute autre logique : l'attente série ne vous bloque jamais
}

Expected Verification

Outdoors (with a clear view of the sky) or near a window, the Native monitor displays complete NMEA frames; the $GNGGA frame appears as soon as the GPS has a fix. Unplugging the GPS does not freeze the loop: the program continues to run (test this with an LED). The module's TX LED blinks during reception.

Common Errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials