shiftIn()

概要

shiftIn()は、1ビットずつ送られてくるデータを取りこみ、1バイトのデータを作成します。

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

ソースコード

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
uint8_t shiftIn(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder) {
    uint8_t value = 0;
    uint8_t i;
 
    for (i = 0; i < 8; ++i) {
        digitalWrite(clockPin, HIGH);
        if (bitOrder == LSBFIRST)
            value |= digitalRead(dataPin) << i;
        else
            value |= digitalRead(dataPin) << (7 - i);
        digitalWrite(clockPin, LOW);
    }
    return value;
}

入力はdataPin、clockPin、bitOrderで、すべてuint8_tです。uint8_tを返します。

1
2
3
uint8_t shiftIn(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder) {
    uint8_t value = 0;
    uint8_t i;

8ビット分のデータを読み取るためループします。最初に、digitalWrite()で、clockPinにHIGHを出力します。

5
6
for (i = 0; i < 8; ++i) {
    digitalWrite(clockPin, HIGH);

次に、digitalRead()で読み取った値を、valueに詰めていきます。

 7
 8
 9
10
11
12
    if (bitOrder == LSBFIRST)
        value |= digitalRead(dataPin) << i;
    else
        value |= digitalRead(dataPin) << (7 - i);
    digitalWrite(clockPin, LOW);
}

bitOrderがLSBFIRSTの場合は最下位ビットから詰めていきます。このため、i番目のループで、valueの第iビットに読み取った値を代入します。bitOrderがLSBFIRSTでない場合は、最上位ビットから詰めていきます。このため、i番目のループで、valueの第(7-i)ビットに読み取った値を代入します。

その後、clockPinにLOWを出力します。

最後に、valueを返却します。

13
14
    return value;
}

shiftIn()は、8ビット固定で読み取るので、異なるビット数の読み取りを行う場合には、このソースを参考にすればいいと思います。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