## **串口事件**
> 本例向你展示**SerialEvent()**函數的使用。本函數將在**loop()**中自動被內部調用。?
> 在我們寫的代碼中如果串口有任何數據(只要不是換行符),那么就將數據加到一個緩存字符串中。在收到換行符時就返回緩存字符串。發送后將會將字符串清空為**null**。
### **所需硬件**
* Arduino板或Genuino板
* 連接線
### **電路**
?
不需要額外電路,但是板子必須連接電腦,Arduino IDE的串口監視器也需要被打開。
### **代碼**
~~~
/*
串口事件
當新的串口數據到來時,我們會將它添加到一個緩存字符串中。當收到換行符時就將緩存字符串
輸出到串口監視器并將字符串清空。
本例程的最好測試方式是使用不斷發送NMEA 0183語句的GPS接收器模塊
代碼公開。
*/
String inputString = ""; // 緩存字符串
boolean stringComplete = false; // 是否string已經完成緩存
void setup() {
// 初始化串口:
Serial.begin(9600);
// 將inputString反轉200個字符:
inputString.reserve(200);
}
void loop() {
// 如果緩存string接收完成:
if (stringComplete) {
Serial.println(inputString);
// 清空String:
inputString = "";
stringComplete = false;
}
}
/*
SerialEvent在arduino板上的RX引腳收到數據時會被系統自動調用。在系統內部,它是在每次loop函數執行時連帶執行的。因此如果再loop使用delay,serialEvent的調用也會被延遲,這樣就有可能一次收到>=2個字符。
*/
void serialEvent() {
while (Serial.available()) {
// 獲取新的字符:
char inChar = (char)Serial.read();
// 將它加到inputString中:
inputString += inChar;
// 如果收到了換行符,就將一個“旗標”變量設置為true,這樣loop函數就知道inputString已經緩存完成了:
if (inChar == '\n') {
stringComplete = true;
}
}
}
~~~
### **相關資料**
[SerialEvent()](https://www.arduino.cc/en/Reference/SerialEvent)?
- 說明
- 系統示例文件目錄結構及說明
- 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