DigitalInputPullup

はじめに

pinMode(INPUT_PULLUP)の使い方を示します。

デジタルの2番ピンから値を読み取り、シリアルモニタに出力します。

プッシュスイッチをデジタルピンの2番とGNDとの間に接続します。

pinMode(INPUT)とは異なり、プルアップ抵抗は必要ありません。内部の20kΩの抵抗で、5Vにプルアップします。この設定では、スイッチが押されていないときHIGHになり、押したときにLOWになります。

プログラム

定義等

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*
  Input Pull-up Serial

  This example demonstrates the use of pinMode(INPUT_PULLUP). It reads a digital
  input on pin 2 and prints the results to the Serial Monitor.

  The circuit:
  - momentary switch attached from pin 2 to ground
  - built-in LED on pin 13

  Unlike pinMode(INPUT), there is no pull-down resistor necessary. An internal
  20K-ohm resistor is pulled to 5V. This configuration causes the input to read
  HIGH when the switch is open, and LOW when it is closed.

  created 14 Mar 2012
  by Scott Fitzgerald

  This example code is in the public domain.

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

特に定義等は行っていません。

setup()

23
24
25
26
27
28
29
30
31
void setup() {
  //start serial connection
  Serial.begin(9600);
  //configure pin 2 as an input and enable the internal pull-up resistor
  pinMode(2, INPUT_PULLUP);
  pinMode(13, OUTPUT);

}
 

Serial.begin()を使って、シリアル通信を行う際の通信速度を設定します。

pinMode()を使って、2番ピンをプルアップモードに、ledPin(13番ピン)を出力モードに設定します。

loop()

32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
void loop() {
  //read the pushbutton value into a variable
  int sensorVal = digitalRead(2);
  //print out the value of the pushbutton
  Serial.println(sensorVal);

  // Keep in mind the pull-up means the pushbutton's logic is inverted. It goes
  // HIGH when it's open, and LOW when it's pressed. Turn on pin 13 when the
  // button's pressed, and off when it's not:
  if (sensorVal == HIGH) {
    digitalWrite(13, LOW);
  } else {
    digitalWrite(13, HIGH);
  }
}

digitalRead()を使って、2番ピンの状態を読み取り、結果をsensorValに代入します。

読み取った値がHIGHであれば、digitalWrite()を使って13番ピンに接続されている内蔵LEDを消します。LOWであれば、点灯します。

バージョン

Hardware:Arduino Uno
Software:Arduino 1.8.16

最終更新日

November 1, 2022

inserted by FC2 system