LoginSignup
4
2

More than 5 years have passed since last update.

Raspberry Pi 3に接続したフォトリフレクタアレイQTR-8RCをNode.jsで使う

Last updated at Posted at 2018-03-05

1. 概要

Raspberry Pi 3からNode.jsを使ってフォトリフレクタアレイQTR-8RCの値を読みます。

スイッチサイエンスで入手できるフォトリフレクタアレイにはアナログ出力タイプのQTR-8Aとデジタル出力タイプのQTR-8RCの2種類があります。

Raspberry Piはアナログ入力がないので、アナログ出力版に以下のようなA/Dコンバータを使うかデジタル出力タイプを使うことになります。

Raspberry PiはSPIがSPI0とSPI1の2つありますが、私の場合はSPI0を別用途で使用していたことと、Node.jsで使っているライブラリのrpioがSPI0しか対応していなかったので、アナログ出力版はあきらめてデジタル出力版を使用しました。
GPIOから簡単に読めるかと思っていたら、少し使い方が違ったのでメモしておきます。

2. 環境、使用機器

3. 参考サイト

  1. Pololu - 5. Module Connections
    • 製造元のサイトの使い方のページ
  2. QTR-1RC using GPIO - Raspberry Pi Forums
    • Raspberry Piのフォーラム

4. 使い方

4.1 配線

QTR-1RC Raspberry Pi 3
GND GND
VCC 5V
LED ON GPIO5 (29)
SENSOR1 GPIO6 (31)

4.2 プログラム

デジタル出力版の方は、センサに手をある程度近づけたら出力が変わるような仕様だと思っていました。簡単に使えると思っていましたが違いました。

参考サイト1の製造元のページでは使い方について以下のように書かれています。

1. Turn on IR LEDs (optional).
2. Set the I/O line to an output and drive it high.
3. Allow at least 10 μs for the sensor output to rise.
4. Make the I/O line an input (high impedance).
5. Measure the time for the voltage to decay by waiting for the I/O line to go low.
6. Turn off IR LEDs (optional).

また参考サイト2のRaspberry Piのフォーラムでも以下のようなサンプルコードがありました。

def Read():
  GPIO.setup(pin, GPIO.OUT) #Set your chosen pin to an output
  GPIO.OUTPUT(pin, True) #Drive the output high, charging the capacitor
  time.sleep(0.01) #wait for the cap to charge. Equations available on wikipedia for working out exact times
  count = 0 # set the counter to 0
  GPIO.setup(pin, GPIO.IN) # set pin to input
  while GPIO.input(pin) == True:
    count = count + 1
  return count

while True:
  Read()
  Print(Read())
  time.sleep(1)

ダメ元でGPIOに繋いで入力を見てみましたが変化はなさそうでした(もしかしたら使えるのかもしれませんが私には分かりませんでした…)。

そこで上のサンプルコードを元にプログラムを書きました。(Node.js勉強中なのでコードの書き方は参考にしないでください。)

index.js
var rpio = require('rpio');
rpio.init({mapping: 'gpio'});

function checkSensor(pin){
  rpio.open(5, rpio.OUTPUT, rpio.HIGH);
  rpio.open(pin, rpio.OUTPUT, rpio.HIGH);
  rpio.sleep(0.01);
  var count = 0;
  rpio.open(pin, rpio.INPUT, rpio.PULL_DOWN);
  while(rpio.read(pin) == 1){
    count++;
  }
  rpio.open(5, rpio.OUTPUT, rpio.LOW);
  return count;
}

setInterval(function(){
  console.log('test = ', checkSensor(6));
},500);

実行結果は以下の通りで、センサに指を近づけると値が小さくなります。

    test = 93
    test = 92
    test = 92
    test = 92
    test = 92
    test = 92
    test = 92
    test = 5
    test = 6
    test = 93
    test = 92
    test = 89
    test = 59
    test = 19
    test = 8
    test = 23
    test = 72
    test = 92

フォトリフレクタが8つついているので、これを順に繰り返していけばとりあえず値は読めそうです。

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2