## **多串口[Mega]**
> 有時候,一個串口遠不能滿足你!當你嘗試和多個串口設備通信,并且還想將數據發送到串口監視器,多幾個RX/TX串口就是你迫切需要的了。本例向你展示Arduino Mega和Genuino Mega上3個附加串口的使用。以及如何將其他串口的數據轉發到TX串口,以此在串口監視器上看到。
### **所需硬件設備**
Arduino Mega板 Genuino Mega板?
串口設備(Xbee板,藍牙模塊或者RFID閱讀器或者另一個Arduino都可以)?
連接線
### **電路**
?
準備好表格上你需要的串口設備后,請確保板子被正常供電并且線路連接正確。串口設備上的**RX**口應該連接到MEGA板上的**TX1**口,串口設備上的**TX**口應該連接到MEGA板上的**RX1**口。如果不清楚,請看原理圖。
你還要確保MEGA板正常通過USB連接到電腦。
### **原理圖**

### **代碼**
下列代碼假定你已經將串口設備連接到板子上的TX1和RX1。
~~~
/*
多串口[Mega]
從主串口獲取數據并且轉發到其他串口。
從串口1獲取數據并且轉發到主串口(串口0)。
代碼只能在串口>=2的設備上使用。比如Arduino Mega、Due、 Zero等。
電路搭建:
* 串口設備連接到串口1
* 串口監視器在串口0打開
代碼是公開的。
*/
void setup() {
// 初始化串口:
Serial.begin(9600);
Serial1.begin(9600);
}
void loop() {
// 從串口1轉發到串口0:
if (Serial1.available()) {
int inByte = Serial1.read();
Serial.write(inByte);
}
// 從串口0轉發到串口1:
if (Serial.available()) {
int inByte = Serial.read();
Serial1.write(inByte);
}
}
~~~
### **相關資料**
[serial.begin()](https://www.arduino.cc/en/Serial/Begin)?
[serial.read()](https://www.arduino.cc/en/Serial/Read)?
[serial.available()](https://www.arduino.cc/en/Serial/Available)?
[if()](https://www.arduino.cc/en/Tutorial/IfStatement)?
- 說明
- 系統示例文件目錄結構及說明
- 01.Basics
- AnalogReadSerial
- BareMinimum
- Blink
- DigitalReadSerial
- Fade
- ReadAnalogVoltage
- 02.Digital
- BlinkWithoutDelay
- Button
- Debounce
- DigitalInputPullup
- StateChangeDetection
- toneKeyboard
- toneMelody
- toneMultiple
- tonePitchFollower
- 03.Analog
- AnalogInOutSerial
- AnalogInput
- AnalogWriteMega
- Calibration
- Fading
- Smoothing
- 04.Communication
- ASCIITable
- Dimmer
- Graph
- Midi
- MultiSerial
- PhysicalPixel
- ReadASCIIString
- SerialCallResponse
- SerialCallResponseASCII
- SerialEvent
- SerialPassthrough
- VirtualColorMixer
- 05.Control
- Arrays
- ForLoopIteration
- IfStatementConditional
- switchCase
- switchCase2
- WhileStatementConditional
- 06.Sensors
- ADXL3xx
- Knock
- Memsic2125
- Ping
- 07.Display
- barGraph
- RowColumnScanning
- 08.Strings
- CharacterAnalysis
- StringAdditionOperator
- StringAppendOperator
- StringCaseChanges
- StringCharacters
- StringComparisonOperators
- StringConstructors
- StringIndexOf
- StringLength
- StringLengthTrim
- StringReplace
- StringStartsWithEndsWith
- StringSubstring
- StringToInt
- 09.USB
- Keyboard
- KeyboardLogout
- KeyboardMessage
- KeyboardReprogram
- KeyboardSerial
- KeyboardAndMouseControl
- Mouse
- ButtonMouseControl
- JoystickMouseControl
- 10.StarterKit_BasicKit (與特定硬件相關,暫無)
- p02_SpaceshipInterface
- p03_LoveOMeter
- p04_ColorMixingLamp
- p05_ServoMoodIndicator
- p06_LightTheremin
- p07_Keyboard
- p08_DigitalHourglass
- p09_MotorizedPinwheel
- p10_Zoetrope
- p11_CrystalBall
- p12_KnockLock
- p13_TouchSensorLamp
- p14_TweakTheArduinoLogo
- p15_HackingButtons
- 11.ArduinoISP(暫無)
- ArduinoISP