🛠 Passerelle série sur les 4 UART matériels

Arduino Mega 2560 (Rev3) · intermediaire · Schéma : IMG-mega-2560-intermediaire-2-passerelle-4-uart.svg — Arduino Mega 2560 reliant le PC (USB/Serial), un module GPS sur Serial1 (19/18), un module sur Serial2 (17/16) et un bus RS-485 sur Serial3 (15/14)

Objectives

Build the signature project for the Mega 2560: communicate with four serial devices simultaneously using its 4 hardware UARTs — something an Uno cannot do (only one UART). Official pin assignments: Serial (0 RX / 1 TX, shared with USB), Serial1 (RX 19 / TX 18), Serial2 (RX 17 / TX 16), Serial3 (RX 15 / TX 14). You will write a non-blocking byte-by-byte router.

Hardware

Respect the TX→RX/RX→TX crossover between the Mega and each module, and ensure a common ground. Warning: the USB-CP link is managed by the ATmega16U2; if the PC writes a lot without anyone reading, the flow can block the board (documented CDC behavior).

Complete Code

// Passerelle 4 UART — PC + GPS + modem + RS-485
void setup {
  Serial.begin(115200);    // console USB (broches 0/1)
  Serial1.begin(9600);     // GPS typique
  Serial2.begin(115200);   // modem typique
  Serial3.begin(9600);     // transceiver RS-485
  while (!Serial && millis < 3000) {}  // attend l'USB CDC
}

void loop {
  // Routage non bloquant, octet par octet :
  if (Serial1.available) Serial.write(Serial1.read);    // GPS -> PC
  if (Serial.available)  Serial2.write(Serial.read);    // PC -> modem
  if (Serial2.available) Serial3.write(Serial2.read);   // modem -> RS-485
  if (Serial3.available) Serial.write(Serial3.read);    // RS-485 -> PC
}

Expected Verification

The serial monitor at 115200 bauds continuously displays the GPS NMEA frames. What you type in the monitor goes to Serial2; the modem's response is relayed to Serial3. No bytes are lost at usual rates because each loop empties the four buffers.

Common Errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials