Arduino入門:シリアル通信

Arduinoでシリアル通信を行う方法について解説します。

Serial.begin

Serial.beginで、シリアル通信のデータ転送レートをBaud Rate(bps)を指定します。bpsはビット/秒で、PCと通信する際は、次のレートから1つを選びます。
300, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, 115200

なお、他の転送レートを必要とするコンポーネントをピン0と1につないで使う場合、上記以外の値を指定することも可能です。

//Arduino Sketch Example: Serial.begin(speed)
//Date: 2015.1.18
//Edited and Modified by: easy labo
//Original Source: Arduino Reference (http://arduino.cc/en/Reference/HomePage)

//Syntax
Serial.begin(speed)
Serial.begin(speed, config)

//Arduino Mega only:
//Serial1.begin(speed) 
//Serial2.begin(speed) 
//Serial3.begin(speed) 
//Serial1.begin(speed, config) 
//Serial2.begin(speed, config) 
//Serial3.begin(speed, config)

//Parameters
/*
speed: in bits per second (baud) - long
config: sets data, parity, and stop bits. Valid values are :

SERIAL_5N1
SERIAL_6N1
SERIAL_7N1
SERIAL_8N1 (the default)
SERIAL_5N2
SERIAL_6N2
SERIAL_7N2
SERIAL_8N2
SERIAL_5E1
SERIAL_6E1
SERIAL_7E1
SERIAL_8E1
SERIAL_5E2
SERIAL_6E2
SERIAL_7E2
SERIAL_8E2
SERIAL_5O1
SERIAL_6O1
SERIAL_7O1
SERIAL_8O1
SERIAL_5O2
SERIAL_6O2
SERIAL_7O2
SERIAL_8O2
*/

//Description
/*
Sets the data rate in bits per second (baud) for serial data transmission. For communicating with the computer, use one of these rates: 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, or 115200. You can, however, specify other rates - for example, to communicate over pins 0 and 1 with a component that requires a particular baud rate.
An optional second argument configures the data, parity, and stop bits. The default is 8 data bits, no parity, one stop bit.
*/

//Example - 1

void setup() {
    Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}

void loop() {}

//Example - 2 ,Arduino Mega example:
// Arduino Mega using all four of its Serial ports 
// (Serial, Serial1, Serial2, Serial3), 
// with different baud rates:

void setup(){
  Serial.begin(9600);
  Serial1.begin(38400);
  Serial2.begin(19200);
  Serial3.begin(4800);

  Serial.println("Hello Computer");
  Serial1.println("Hello Serial 1");
  Serial2.println("Hello Serial 2");
  Serial3.println("Hello Serial 3");
}

void loop() {}

Creative Commons Attribution-ShareAlike 3.0 License (CC BY-SA 3.0)
Arduino Reference:Serial.begin()” by Arduino Team, used under CC BY-SA 3.0/ easy labo made some changes and comments to the original

上のExample-1では、9600bpsでポートを開いています。次のExample-2は、Arduino Megaの例で、4つのシリアルポート(Serial, Serial1, Serial2, Serial3)を異なる転送レートで初期化しています。

Serial.end

Serial.endは、シリアル通信を終了します。RXとTXを汎用の入出力ピンとして使えるようにします。

//Arduino Sketch Example: Serial.end()
//Date: 2015.1.18
//Edited and Modified by: easy labo
//Original Source: Arduino Reference (http://arduino.cc/en/Reference/HomePage)

//Syntax
Serial.end()

//Arduino Mega only: 
//Serial1.end() 
//Serial2.end() 
//Serial3.end()

//Description
/*
Disables serial communication, allowing the RX and TX pins to be used for general input and output. To re-enable serial communication, call Serial.begin().
*/

Creative Commons Attribution-ShareAlike 3.0 License (CC BY-SA 3.0)
Arduino Reference:Serial.end()” by Arduino Team, used under CC BY-SA 3.0/ easy labo made some changes and comments to the original

Serial.available

Serial.availableは、シリアルポートに何バイトのデータが到着しているかを返します。バッファには128バイトまで保持できます。

//Arduino Sketch Example: Serial.available()
//Date: 2015.1.18
//Edited and Modified by: easy labo
//Original Source: Arduino Reference (http://arduino.cc/en/Reference/HomePage)

//Syntax
Serial.available()

//Arduino Mega only: 
//Serial1.available() 
//Serial2.available() 
//Serial3.available()

//Description
/*
Get the number of bytes (characters) available for reading from the serial port. This is data that's already arrived and stored in the serial receive buffer (which holds 64 bytes). available() inherits from the Stream utility class.
*/

//Example - 1
int incomingByte = 0;   // for incoming serial data

void setup() {
        Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
}

void loop() {

        // send data only when you receive data:
        if (Serial.available() > 0) {
                // read the incoming byte:
                incomingByte = Serial.read();

                // say what you got:
                Serial.print("I received: ");
                Serial.println(incomingByte, DEC);
        }
}

//Example - 2, Arduino Mega
void setup() {
  Serial.begin(9600);
  Serial1.begin(9600);

}

void loop() {
  // read from port 0, send to port 1:
  if (Serial.available()) {
    int inByte = Serial.read();
    Serial1.print(inByte, BYTE); 

  }
  // read from port 1, send to port 0:
  if (Serial1.available()) {
    int inByte = Serial1.read();
    Serial.print(inByte, BYTE); 
  }
}

Creative Commons Attribution-ShareAlike 3.0 License (CC BY-SA 3.0)
Arduino Reference:Serial.available()” by Arduino Team, used under CC BY-SA 3.0/ easy labo made some changes and comments to the original

上のサンプルコードは、Example-1が通常のArduinoボード、Example-2がArduino Megaボードの使用例です。

Serial.read

Serial.readは、受信データを読み込みます。読み込み可能なデータの最初の1バイトを返しますが、-1の場合は、データが存在しません。

//Arduino Sketch Example: Serial.read()
//Date: 2015.1.18
//Edited and Modified by: easy labo
//Original Source: Arduino Reference (http://arduino.cc/en/Reference/HomePage)

//Syntax
Serial.read()

//Arduino Mega only: 
//Serial1.read() 
//Serial2.read() 
//Serial3.read()

//Returns
//the first byte of incoming serial data available (or -1 if no data is available) - int
//Description
//Reads incoming serial data. read() inherits from the Stream utility class.

//Example

int incomingByte = 0;   // for incoming serial data

void setup() {
        Serial.begin(9600);   // opens serial port, sets data rate to 9600 bps
}

void loop() {

        // send data only when you receive data:
        if (Serial.available() > 0) {
                // read the incoming byte:
                incomingByte = Serial.read();

                // say what you got:
                Serial.print("I received: ");
                Serial.println(incomingByte, DEC);
        }
}

Creative Commons Attribution-ShareAlike 3.0 License (CC BY-SA 3.0)
Arduino Reference:Serial.read()” by Arduino Team, used under CC BY-SA 3.0/ easy labo made some changes and comments to the original

上の例では、Serial.availableで受信状況を確認し、incomingByteにSerial.readで読み取ったデータを格納しています。

Serial.peek

Serial.peekは、受信データを1バイト読み込みます。ただし、読みだしたデータはバッファから受信データは削除されず、またバッファ中の読み取り位置は変更しません。つまり、Serial.peekを繰り返し使用しても同じ文字を繰り返し読み取る事になります。Serial.peekは、読み込み可能なデータの最初の1バイトを返します。-1の場合は、データが存在しません。

//Arduino Sketch Example: Serial.peek()
//Date: 2015.1.18
//Edited and Modified by: easy labo
//Original Source: Arduino Reference (http://arduino.cc/en/Reference/HomePage)

//Syntax
Serial.peek()

//Arduino Mega only: 
//Serial1.peek() 
//Serial2.peek() 
//Serial3.peek()

//Returns
/the first byte of incoming serial data available (or -1 if no data is available) - int

//Description
/*
Returns the next byte (character) of incoming serial data without removing it from the internal serial buffer. That is, successive calls to peek() will return the same character, as will the next call to read(). peek() inherits from the Stream utility class.
*/

Creative Commons Attribution-ShareAlike 3.0 License (CC BY-SA 3.0)
Arduino Reference:Serial.peek()” by Arduino Team, used under CC BY-SA 3.0/ easy labo made some changes and comments to the original

Serial.flush

Serial.flushは、シリアルデータの送信が完了するまで待機を指示します。

//Arduino Sketch Example: Serial.flush()
//Date: 2015.1.18
//Edited and Modified by: easy labo
//Original Source: Arduino Reference (http://arduino.cc/en/Reference/HomePage)

//Syntax
Serial.flush()

//Arduino Mega only: 
//Serial1.flush() 
//Serial2.flush() 
//Serial3.flush()

//Description
//Waits for the transmission of outgoing serial data to complete. (Prior to Arduino 1.0, this instead removed any buffered incoming serial data.)
//flush() inherits from the Stream utility class.

Creative Commons Attribution-ShareAlike 3.0 License (CC BY-SA 3.0)
Arduino Reference:Serial.flush()” by Arduino Team, used under CC BY-SA 3.0/ easy labo made some changes and comments to the original

Arduino 1.0以前では、上記の処理と違って受信バッファをクリアする仕様でしたので注意が必要です。

Serial.print

ASCIIフォーマットでデータをシリアルポートへ出力します。 数値は1桁ずつASCII文字に変換されます。浮動小数点数の場合は、デフォルトで小数点以下第2位まで出力されます。またバイト型のデータは1文字として送信され、文字列はそのまま送信されます。設定パラメータは次の通りです。

data: 出力する値。すべての型に対応しています。
format: 基数または有効桁数(浮動小数点数の場合)

送信後、送信したバイト数を返します。

//Arduino Sketch Example: Serial.print(data, format)
//Date: 2015.1.18
//Edited and Modified by: easy labo
//Original Source: Arduino Reference (http://arduino.cc/en/Reference/HomePage)

//Syntax
Serial.print(val) 
Serial.print(val, format)

//Parameters
//val: the value to print - any data type

//format: specifies the number base (for integral data types) or number of decimal places (for floating point types)

//Returns
//size_t (long): print() returns the number of bytes written, though reading that number is optional

//Example:

/*
Uses a FOR loop for data and prints a number in various formats.
*/
int x = 0;    // variable

void setup() {
  Serial.begin(9600);      // open the serial port at 9600 bps:    
}

void loop() {  
  // print labels 
  Serial.print("NO FORMAT");       // prints a label
  Serial.print("\t");              // prints a tab

  Serial.print("DEC");  
  Serial.print("\t");      

  Serial.print("HEX"); 
  Serial.print("\t");   

  Serial.print("OCT");
  Serial.print("\t");

  Serial.print("BIN");
  Serial.print("\t"); 

  for(x=0; x< 64; x++){    // only part of the ASCII chart, change to suit

    // print it out in many formats:
    Serial.print(x);       // print as an ASCII-encoded decimal - same as "DEC"
    Serial.print("\t");    // prints a tab

    Serial.print(x, DEC);  // print as an ASCII-encoded decimal
    Serial.print("\t");    // prints a tab

    Serial.print(x, HEX);  // print as an ASCII-encoded hexadecimal
    Serial.print("\t");    // prints a tab

    Serial.print(x, OCT);  // print as an ASCII-encoded octal
    Serial.print("\t");    // prints a tab

    Serial.println(x, BIN);  // print as an ASCII-encoded binary
    //                             then adds the carriage return with "println"
    delay(200);            // delay 200 milliseconds
  }
  Serial.println("");      // prints another carriage return
}

Creative Commons Attribution-ShareAlike 3.0 License (CC BY-SA 3.0)
Arduino Reference:Serial.print(data, format)” by Arduino Team, used under CC BY-SA 3.0/ easy labo made some changes and comments to the original

上の例に加えて、様々な出力例を挙げておきます。

//Arduino Sketch Example: Serial.print(data, format)
//Date: 2015.1.18
//Edited and Modified by: easy labo
//Original Source: Arduino Reference (http://arduino.cc/en/Reference/HomePage)

/*
Serial.print(78) gives "78"
Serial.print(1.23456) gives "1.23"
Serial.print('N') gives "N"
Serial.print("Hello world.") gives "Hello world."

Serial.print(78, BIN) gives "1001110"
Serial.print(78, OCT) gives "116"
Serial.print(78, DEC) gives "78"
Serial.print(78, HEX) gives "4E"

Serial.println(1.23456, 0) gives "1"
Serial.println(1.23456, 2) gives "1.23"
Serial.println(1.23456, 4) gives "1.2346"
*/

Creative Commons Attribution-ShareAlike 3.0 License (CC BY-SA 3.0)
Arduino Reference:Serial.print(data, format)” by Arduino Team, used under CC BY-SA 3.0/ easy labo made some changes and comments to the original

println

Serial.printlnは、データの末尾に改行コードをつけて送信します。改行コードとして、キャリッジリターン(ASCIIコード13あるいは’\r’)とニューライン(ASCIIコード10あるいは’\n’)を付けられます。なお、Serial.print()と同じフォーマットが使えます。

//Arduino Sketch Example: println
//Date: 2015.1.18
//Edited and Modified by: easy labo
//Original Source: Arduino Reference (http://arduino.cc/en/Reference/HomePage)

//Syntax
Serial.println(val) 
Serial.println(val, format)

//Parameters
//val: the value to print - any data type
//format: specifies the number base (for integral data types) or //number of decimal places (for floating point types)

//Returns
//size_t (long): println() returns the number of bytes written, though reading that number is optional
//Description
/*
Prints data to the serial port as human-readable ASCII text followed by a carriage return character (ASCII 13, or '\r') and a newline character (ASCII 10, or '\n'). This command takes the same forms as Serial.print().
*/

/Example:
/*
  Analog input reads an analog input on analog in 0, prints the value out.
created 24 March 2006 by Tom Igoe
*/

int analogValue = 0;    // variable to hold the analog value

void setup() {
  // open the serial port at 9600 bps:
  Serial.begin(9600);
}

void loop() {
  // read the analog input on pin 0:
  analogValue = analogRead(0);

  // print it out in many formats:
  Serial.println(analogValue);       // print as an ASCII-encoded decimal
  Serial.println(analogValue, DEC);  // print as an ASCII-encoded decimal
  Serial.println(analogValue, HEX);  // print as an ASCII-encoded hexadecimal
  Serial.println(analogValue, OCT);  // print as an ASCII-encoded octal
  Serial.println(analogValue, BIN);  // print as an ASCII-encoded binary

  // delay 10 milliseconds before the next reading:
  delay(10);
}

Creative Commons Attribution-ShareAlike 3.0 License (CC BY-SA 3.0)
Arduino Reference:println()” by Arduino Team, used under CC BY-SA 3.0/ easy labo made some changes and comments to the original

上の例では、アナログ入力の値を様々なフォーマットで送信します。この例ではデータごとに改行されます。上記に加えて幾つかの出力例を次に挙げておきます。

//Arduino Sketch Example: Serial.println(data, format)
//Date: 2015.1.18
//Edited and Modified by: easy labo
//Original Source: Arduino Reference (http://arduino.cc/en/Reference/HomePage)

/*
Serial.println(1.23456, 0) gives "1"
Serial.println(1.23456, 2) gives "1.23"
Serial.println(1.23456, 4) gives "1.2346"
*/

Creative Commons Attribution-ShareAlike 3.0 License (CC BY-SA 3.0)
Arduino Reference:Serial.print(data, format)” by Arduino Team, used under CC BY-SA 3.0/ easy labo made some changes and comments to the original

Serial.write

Serial.writeは、シリアルポートにバイナリデータを出力します。1バイトずつ、あるいは複数バイトの送信が可能です。設定パラメータは次の通りです。

val: 送信する値(1バイト)
str: 文字列(複数バイト)
buf: 配列として定義された複数のバイト
len: 配列の長さ

なおSerial.writeは、送信後に送信したバイト数を返します。

//Arduino Sketch Example: Serial.write
//Date: 2015.1.18
//Edited and Modified by: easy labo
//Original Source: Arduino Reference (http://arduino.cc/en/Reference/HomePage)

//Syntax
Serial.write(val) 
Serial.write(str) 
Serial.write(buf, len)

//Arduino Mega also supports: Serial1, Serial2, Serial3 (in place of Serial)

//Parameters
//val: a value to send as a single byte
//str: a string to send as a series of bytes
//buf: an array to send as a series of bytes
//len: the length of the buffer

//Returns
//byte write() will return the number of bytes written, though reading that number is optional
//Description
/*
Writes binary data to the serial port. This data is sent as a byte or series of bytes; to send the characters representing the digits of a number use the print() function instead.
*/

//Example

void setup(){
  Serial.begin(9600);
}

void loop(){
  Serial.write(45); // send a byte with the value 45

   int bytesSent = Serial.write(“hello”); //send the string “hello” and return the length of the string.
}

Creative Commons Attribution-ShareAlike 3.0 License (CC BY-SA 3.0)
Arduino Reference:Serial.write()” by Arduino Team, used under CC BY-SA 3.0/ easy labo made some changes and comments to the original

数値を表す文字(列)として送信したい場合は、Serial.printを使う必要がありますので注意してください。

→その他のArduino関連情報

Sponsored Link