ReadASCIIString

はじめに

parseInt()を使い、シリアルデータから整数値を読み出します。

プログラム

定義等

 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
27
28
/*
  Reading a serial ASCII-encoded string.

  This sketch demonstrates the Serial parseInt() function.
  It looks for an ASCII string of comma-separated values.
  It parses them into ints, and uses those to fade an RGB LED.

  Circuit: Common-Cathode RGB LED wired like so:
  - red anode: digital pin 3 through 220 ohm resistor
  - green anode: digital pin 5 through 220 ohm resistor
  - blue anode: digital pin 6 through 220 ohm resistor
  - cathode: GND

  created 13 Apr 2012
  by Tom Igoe
  modified 14 Mar 2016
  by Arturo Guadalupi

  This example code is in the public domain.

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

// pins for the LEDs:
const int redPin = 3;
const int greenPin = 5;
const int bluePin = 6;
  

const int型の変数redPinとgreenPin、bluePinを定義し、初期化します。

setup()

29
30
31
32
33
34
35
36
37
38
void setup() {
  // initialize serial:
  Serial.begin(9600);
  // make the pins outputs:
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);

}
 

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

pinMode()で、redPinとgreenPin、bluePinを出力モードにします。

loop()

39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
void loop() {
  // if there's any serial available, read it:
  while (Serial.available() > 0) {

    // look for the next valid integer in the incoming serial stream:
    int red = Serial.parseInt();
    // do it again:
    int green = Serial.parseInt();
    // do it again:
    int blue = Serial.parseInt();

    // look for the newline. That's the end of your sentence:
    if (Serial.read() == '\n') {
      // constrain the values to 0 - 255 and invert
      // if you're using a common-cathode LED, just use "constrain(color, 0, 255);"
      red = 255 - constrain(red, 0, 255);
      green = 255 - constrain(green, 0, 255);
      blue = 255 - constrain(blue, 0, 255);

      // fade the red, green, and blue legs of the LED:
      analogWrite(redPin, red);
      analogWrite(greenPin, green);
      analogWrite(bluePin, blue);

      // print the three numbers in one string as hexadecimal:
      Serial.print(red, HEX);
      Serial.print(green, HEX);
      Serial.println(blue, HEX);
    }
  }
}

Serial.available()で、シリアル入力があるかを調べます。入力がある場合、Serial.parseInt()を使い、読み取った文字列を整数に変換し、それぞれ、redとgreen、blueに代入します。3つの数値が送られてくる想定です。数値と数値の間には整数でない文字(たとえば、「,」)が必要です。

次に読み取った文字が’\n’であれば、送られた文字列が正しいものとして以下の処理を行います。

読み取った数値を、constrain()を使って、0から255の範囲に制限し、255から引いたものをredとgreen、blueに代入します。

計算した値をanalogWrite()を使って、ピンに出力します。

最後に、Serial.print()で、シリアルコンソールに読み取った値を16進数で出力します。

バージョン

Hardware:Arduino Uno
Software:Arduino 1.8.16

最終更新日

September 11, 2021

inserted by FC2 system