shiftOut()

概要

shiftOut()は、1バイトのデータを、1ビットずつ送信します。

shiftOut()のリファレンスはこちらをご覧ください。

ソースコード

shiftOut()は、hardware/arduino/avr/cores/arduino/wiring_shift.c に定義されています。以下に全ソースコードを示します。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
{
        uint8_t i;

        for (i = 0; i < 8; i++)  {
                if (bitOrder == LSBFIRST) {
                        digitalWrite(dataPin, val & 1);
                        val >>= 1;
                } else {
                        digitalWrite(dataPin, (val & 128) != 0);
                        val <<= 1;
                }

                digitalWrite(clockPin, HIGH);
                digitalWrite(clockPin, LOW);
        }
}

入力はdataPin、clockPin、bitOrder、valで、すべてuint8_tです。戻り値はありません。

1
2
3
void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
{
    uint8_t i;

8ビット分のデータを書き出すためループします。その中で、1ビットずつ値を出力します。

 5
 6
 7
 8
 9
10
11
12
        for (i = 0; i < 8; i++)  {
                if (bitOrder == LSBFIRST) {
                        digitalWrite(dataPin, val & 1);
                        val >>= 1;
                } else {
                        digitalWrite(dataPin, (val & 128) != 0);
                        val <<= 1;
                }

bitOrderがLSBFIRSTの場合は、入力値valの最下位ビットから1ビットずつ送信します。valと1のビット単位ANDをとり、valの第0ビットを送信します。その後、valを右に1ビットシフトすることで、次に送信するビットを、valの第0ビットになるようにします。

bitOrderがLSBFIRSTでない場合は、入力値valの最上位ビットから1ビットずつ送信します。valと128(=0B10000000)のビット単位ANDをとり、valの第7ビットを送信します。その後、valを左に1ビットシフトすることで、次に送信するビットを、valの第7ビットになるようにします。

値の送信には、digitalWrite()を使います。

最後に、clockPinをHIGHにし、直後にLOWとすることで、パルスを一つ送信します。

14
15
16
17
        digitalWrite(clockPin, HIGH);
        digitalWrite(clockPin, LOW);        
    }
}

shiftOut()は、8ビット固定で書き出すので、異なるビット数の書き出しを行う場合には、このソースを参考にすればいいと思います。

バージョン

Arduino AVR Boards 1.8.6

ライセンス

 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
/*
  Copyright (c) 2016 garretlab.
  Added source code explanation by garretlab.
*/

/*
  wiring_shift.c - shiftOut() function
  Part of Arduino - http://www.arduino.cc/

  Copyright (c) 2005-2006 David A. Mellis

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General
  Public License along with this library; if not, write to the
  Free Software Foundation, Inc., 59 Temple Place, Suite 330,
  Boston, MA  02111-1307  USA
*/

最終更新日

July 31, 2025

inserted by FC2 system