SerialPassthrough

はじめに

一つのシリアルポートから受信したデータをもう一つのシリアルポートに送信します。

Arduino MegaやDue、Zeroなど、複数のシリアルを持つボード向けのプログラムです。

MultiSerialと同じ内容です。

プログラム

定義等

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/*
  SerialPassthrough sketch

  Some boards, like the Arduino 101, the MKR1000, Zero, or the Micro, have one
  hardware serial port attached to Digital pins 0-1, and a separate USB serial
  port attached to the IDE Serial Monitor. This means that the "serial
  passthrough" which is possible with the Arduino UNO (commonly used to interact
  with devices/shields that require configuration via serial AT commands) will
  not work by default.

  This sketch allows you to emulate the serial passthrough behaviour. Any text
  you type in the IDE Serial monitor will be written out to the serial port on
  Digital pins 0 and 1, and vice-versa.

  On the 101, MKR1000, Zero, and Micro, "Serial" refers to the USB Serial port
  attached to the Serial Monitor, and "Serial1" refers to the hardware serial
  port attached to pins 0 and 1. This sketch will emulate Serial passthrough
  using those two Serial ports on the boards mentioned above, but you can change
  these names to connect any two serial ports on a board that has multiple ports.

  created 23 May 2016
  by Erik Nyquist

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

このプログラムでは特に何もしていません。

setup()

27
28
29
30
31
void setup() {
  Serial.begin(9600);
  Serial1.begin(9600);
}
 

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

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

loop()

32
33
34
35
36
37
38
39
40
void loop() {
  if (Serial.available()) {      // If anything comes in Serial (USB),
    Serial1.write(Serial.read());   // read it and send it out Serial1 (pins 0 & 1)
  }

  if (Serial1.available()) {     // If anything comes in Serial1 (pins 0 & 1)
    Serial.write(Serial1.read());   // read it and send it out Serial (USB)
  }
}

Serial.available()でSerialのデータが利用できるかを調べ、利用可能であればSerial.read()でデータを読みます。Seral1.write()で、もう一方のシリアルポートに読んだデータを送信します。

また、Serial1から読んだ値をSerialに送信しています。

バージョン

Hardware:Arduino Mega/Arduino Due/Arduino Zero
Software:Arduino 1.8.16

最終更新日

September 11, 2021

inserted by FC2 system