Last-modified: 2016-04-10 (日) 16:41:28
Raspberry Pi/タクトスイッチ

概要

Raspberry Pi2のGPIOでタクトスイッチを使ってみます。

配線

000022.png

R2はプルダウン抵抗して動作する。
プルダウン抵抗は、ラインに何も接続されていない時に、そのラインの電位をLowレベルに固定する目的で使う。
また、電源とGPIO24の間に抵抗を挟む場合は、プルアップ抵抗と呼ばれる。
プルアップ抵抗は、ラインに何も接続されていない時に、そのラインの電位をHighレベルに固定する目的で使う。
プルダウン, プルアップ抵抗いずれかを用いないと、ラインに何も接続していない時の状態が不定になる。
ただし、Raspberry Pi2(BCM2836)のGPIOはデフォルトで不定以外の状態になっている。
http://elinux.org/RPi_BCM2835_GPIOs
または、

Everything is expanded.Everything is shortened.
  1
 
gpio readall

写真の回路では自前のプルダウン抵抗を用意しているが、本来不要。

000001.jpg

手順

  1. vi app.cpp
    Everything is expanded.Everything is shortened.
      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
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
    
     
     
     
     
     
     
     
     
    -
    |
    |
    |
    !
     
    -
    |
    |
    |
    !
     
    -
    |
    -
    |
    -
    |
    !
    |
    -
    |
    !
    |
    |
    -
    |
    |
    !
    !
    |
    -
    |
    !
    |
    -
    |
    !
    |
    !
    
    #include <iostream>
    #include <stdexcept>
    #include <thread>
    #include <wiringPi.h>
     
    using namespace std;
     
    namespace
    {
        constexpr int InPin = 24;
        constexpr int OutPin = 25;
        constexpr int WaitMicroSec = 10 * 1000;
    };
     
    /**
     * @brief タクトスイッチのオン/オフでLEDを点灯 
     * 
     * @return 常に0
     */
    int main()
    {
        try
        {
            if (wiringPiSetupGpio() == -1)
            {
                throw runtime_error("Failed to wiringPiSetupGpio");
            }
            pinMode(InPin, INPUT);
            // 明示的にプルアップ,プルダウンを指定したい場合に使う
            // pullUpDnControl(InPin, PUD_DOWN);
            pinMode(OutPin, OUTPUT);
     
            for (;;)
            {
                digitalWrite(OutPin, digitalRead(InPin));
                this_thread::sleep_for(chrono::microseconds(WaitMicroSec));
            }
        }
        catch (exception& e)
        {
            cerr << e.what() << "\n";
        }
        catch (...)
        {
            cerr << "Unknown exception!\n";
        }
        return 0;
    }
  2. vi Makefile
    Everything is expanded.Everything is shortened.
      1
      2
      3
      4
    
     
     
     
     
    
    app: app.cpp
        g++ app.cpp -O2 -Wall -Wextra -std=gnu++11 -lwiringPi -oapp
    clean:
        rm -f *.o app
  3. ビルド/実行
    Everything is expanded.Everything is shortened.
      1
      2
    
     
     
    
    make
    sudo ./app

検証時の環境