🛠 Passerelle série sur les 4 UART matériels
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
- 1 × Arduino Mega 2560 + USB cable
- 1 × GPS module (typically 9600 bauds) on Serial1
- 1 × modem module or second device (typically 115200) on Serial2
- 1 × RS-485 transceiver (or any 9600 device) on Serial3
- Breadboard and wires
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
- Confusing the pairs: Serial1 = 19/18, Serial2 = 17/16, Serial3 = 15/14 (RX/TX in this order) — not pins 10/11 of the SPI.
- Connecting TX to TX instead of TX to RX crossed: nothing passes, or worse, line conflict.
- Forgetting the common ground between separately powered modules: corrupted data.
- Flooding the USB port without reading it: the board may stop responding over USB (specificity of the 16U2's CDC flow control); limit the rate or read on the PC side.
Other tutorials for this board
Code examples for this board
clignotante.inoArduinobouton-led.inoArduinodouble-servo.inoArduinopont-uart.inoArduinopwm-respiration.inoArduinopotentiometre-plotter.inoArduino