DigitalReadSerial

はじめに

デジタルピン(2番ピン)から読み取った値をシリアルモニタに出力します。

プログラム

定義等

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
/*
  DigitalReadSerial

  Reads a digital input on pin 2, prints the result to the Serial Monitor

  This example code is in the public domain.

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

// digital pin 2 has a pushbutton attached to it. Give it a name:
int pushButton = 2;
 

pushButtonを2に初期化します。

setup()

14
15
16
17
18
19
20
21
// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
  // make the pushbutton's pin an input:
  pinMode(pushButton, INPUT);
}
 

Serialは、Arduinoソフトウェアにより事前に定義されている変数(C++のオブジェクト)です。シリアルモニタと通信を行うときに利用します。Serial.begin()により、通信速度を設定(今は9600bps)します。

pinMode(pushButton, INPUT)で、デジタルピンの2番を入力モードに設定します。pushButtonは、最初に2で初期化しています。

loop()

22
23
24
25
26
27
28
29
// the loop routine runs over and over again forever:
void loop() {
  // read the input pin:
  int buttonState = digitalRead(pushButton);
  // print out the state of the button:
  Serial.println(buttonState);
  delay(1);        // delay in between reads for stability
}

buttonStateは、int型の変数で、その値を、digitalRead(pushButton)の結果で初期化します。すなわち、デジタルピンの2番ピンの値を読みこみます。

読み取った値(sensorValue)を、Serial.println()を使い、シリアルモニタに表示します。

バージョン

Hardware:Arduino Uno
Software:Arduino 1.8.16

最終更新日

September 11, 2021

inserted by FC2 system