Use Multiple Serial Ports on the Arduino Mega

Use two of the serial ports available on the Arduino Mega.

Sometimes, one serial port just isn't enough! When trying to communicate with multiple serial enabled devices, while also sending info back to the main serial window, a few extra RX/TX ports can be a welcomed thing. This example makes use of one of Arduino Mega's 3 auxiliary serial ports, routing any incoming data read on that connection straight to the main TX line, and, in turn, to the main serial window for you to view.

Hardware Required

  • Arduino Mega Board

  • Serial enabled device (a Xbee Radio, a Bluetooth® module, or RFID reader, or another board, for instance).

Circuit

After checking the data sheet of whatever serial enabled device you choose to use for this example, make sure that it is both properly wired and powered. Connect the RX pin and TX pins of your device to the TX1 and RX1 pins of your Mega, as shown in the schematic below.

Make sure that your Mega is connected to your computer, via USB, to enable serial communication.

circuit

Schematic

schematic

Code

This sketch assumes that you connect your serial enabled device is attached to TX1 and RX1.

1/*
2
3 Multiple Serial test
4
5 Receives from the main serial port, sends to the others.
6
7 Receives from serial port 1, sends to the main serial (Serial 0).
8
9 This example works only with boards with more than one serial like Arduino Mega, Due, Zero etc.
10
11 The circuit:
12
13 - any serial device attached to Serial port 1
14
15 - Serial Monitor open on Serial port 0
16
17 created 30 Dec 2008
18
19 modified 20 May 2012
20
21 by Tom Igoe & Jed Roach
22
23 modified 27 Nov 2015
24
25 by Arturo Guadalupi
26
27 This example code is in the public domain.
28
29*/
30
31void setup() {
32
33 // initialize both serial ports:
34
35 Serial.begin(9600);
36
37 Serial1.begin(9600);
38}
39
40void loop() {
41
42 // read from port 1, send to port 0:
43
44 if (Serial1.available()) {
45
46 int inByte = Serial1.read();
47
48 Serial.write(inByte);
49
50 }
51
52 // read from port 0, send to port 1:
53
54 if (Serial.available()) {
55
56 int inByte = Serial.read();
57
58 Serial1.write(inByte);
59
60 }
61}

Learn more

You can find more basic tutorials in the built-in examples section.

You can also explore the language reference, a detailed collection of the Arduino programming language.

Last revision 2015/07/29 by SM

Suggest changes

The content on docs.arduino.cc is facilitated through a public GitHub repository. If you see anything wrong, you can edit this page here.

License

The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.