SerialEvent

はじめに

シリアルデータを受信すると文字列に追加します。改行コードを受信すると文字列を表示し、その後、文字列をクリアします。

プログラム

定義等

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
  Serial Event example

  When new serial data arrives, this sketch adds it to a String.
  When a newline is received, the loop prints the string and clears it.

  A good test for this is to try it with a GPS receiver that sends out
  NMEA 0183 sentences.

  NOTE: The serialEvent() feature is not available on the Leonardo, Micro, or
  other ATmega32U4 based boards.

  created 9 May 2011
  by Tom Igoe

  This example code is in the public domain.

  https://www.arduino.cc/en/Tutorial/BuiltInExamples/SerialEvent
*/

String inputString = "";         // a String to hold incoming data
bool stringComplete = false;  // whether the string is complete
  

String 型の変数inputStringとboolean型の変数stringCompleteを定義し、それぞれ、““とfalseで初期化します。

setup()

24
25
26
27
28
29
30
void setup() {
  // initialize serial:
  Serial.begin(9600);
  // reserve 200 bytes for the inputString:
  inputString.reserve(200);
}
 

Serial.begin()を使って、シリアルポートを初期化します。

inputString.reserve()を使って、文字列を格納する領域を200バイト確保します。この関数は、現在確保している領域が引数で指定したバイト数よりも小さいときには、領域を拡張します。

loop()

31
32
33
34
35
36
37
38
39
40
void loop() {
  // print the string when a newline arrives:
  if (stringComplete) {
    Serial.println(inputString);
    // clear the string:
    inputString = "";
    stringComplete = false;
  }
}
  

stringCompleteがfalseでなければ(trueだったら)、Serial.println()を使ってinputStringを表示して、inputStringに"“を代入し、stringCompleteをfalseにします。stringCompleteがfalseであればなにもしません。stringCompleteやinputStringは、SerialEvent()の中で設定しています。

SerialEvent()

SerialEvent()は、Arduino 1.0から導入された機構です。loop()を実行するたびに、void SerialEventRun(void)というArduinoソフトウェアが定義した関数が呼ばれます。その中ではSerial.available()でシリアルポートにデータが到着しているかを確認し、到着していれば、void SerialEvent(void)という関数を呼び出します。

Arduino Megaでは、Serial1、Serial2、Serial3に対して、SerialEvent1()、SerialEvent2()、SerialEvent3()という関数が実行されます。

41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
  SerialEvent occurs whenever a new data comes in the hardware serial RX. This
  routine is run between each time loop() runs, so using delay inside loop can
  delay response. Multiple bytes of data may be available.
*/
void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag so the main loop can
    // do something about it:
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
}

Serial.available()が0でない間、Serial.read()でシリアルポートから文字を読み取り、inputStringに追加します。Stringクラスでは、+演算子をオーバーライドしており、足し算を使って、もとの文字列に指定した文字を追加することができます。

また、読み取った文字が’\n’(改行コード)であれば、stringCompleteにtrueを代入します。

バージョン

Hardware:Arduino Uno
Software:Arduino 1.8.16

最終更新日

September 11, 2021

inserted by FC2 system