LoginSignup
0
3

More than 5 years have passed since last update.

⑤Raspberry Pi3と土壌湿度センサーで土壌湿度を取得する(YL69 + MCP3002)

Posted at

準備するもの(周辺機器)

1.Raspberry Pi 3
2.YL-69(土壌湿度センサー)
3.MCP3002(A/D コンバータ)
4.オスジャンパー、メスジャンパー(Raspberry Pi初心者キット使用)

A/D コンバータとは

Raspberry Piはアナログデータを読み取ることができません。
A/Dコンバータはアナログデータを1と0の2進数に変換し、Raspberry Piに通信で送信するデバイスです。
Raspberry PiとA/Dコンバータの間の通信は、SPI通信を使用します。

Raspberry PiでSPI通信の設定

SPI通信のドライバをインストール

$ sudo apt-get install python-spidev

「5.Interfacing Options」を選択
スクリーンショット 2018-08-28 11.57.06.png

「P4 SPI」を選択
スクリーンショット 2018-08-28 11.57.22.png

SPIが有効かの確認

ls -l /dev/spi*

yl69+MCP3208+ブレッドボード+Raspberry Piを接続

スクリーンショット 2018-08-28 11.53.33.png

スクリプト作成

yl69.py
# -*- coding: utf-8 -*-
import RPi.GPIO as GPIO
from time import sleep
import spidev

#GPIOのピン番号
pin = 22

# initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()

#GPIOの指定したピン番号を出力端子に設定
GPIO.setup(pin, GPIO.OUT)

#出力用関数
def output_fromGPIO(pin, output):
    GPIO.output(pin, output)
    sleep(0.1)

#MCP3002動作用関数
def readadc_spidev(adcnum):
    if ((adcnum > 1) or (adcnum < 0)):
        return -1
    #0x68は1chを使う場合です。2chは0x78を使います。
    ret = spi.xfer2([0x68,0x00])    
    #データは8ビットずつに分かれているので、最初の8ビットを上位データとして8ビットシフトし、下位データと結合する
    #MCP3002は10ビット目までがデータなので、10ビット目までを残して他のデータを消す
    adcout = ((ret[0]<<8) + ret[1])&0x3ff
    return adcout

#SPI通信開始
spi=spidev.SpiDev()
spi.open(0, 0) # bus0, CE0

#データ取得前にYL-69に電圧を印可
output_fromGPIO(pin,True)

try:
    while True:
        #先ほど定義したMCP3002の関数を呼び出す
        getValue = readadc_spidev(0)
        #値がちゃんと取れたらデータを出力。取れるまでトライ
        if getValue != -1:
            print(getValue)
            break;
        sleep(1)

except KeyboardInterrupt:
    pass

#YL-69の印加電圧をとめる
output_fromGPIO(pin,False)
#SPI通信終了
spi.close()

スクリプト実行

sudo python yl69.py
>>> 1023
>>> 464
>>> 699

成功!!

0
3
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
0
3