ADS1015 について
Raspberry Pi には A/D コンバータが内蔵されていません。デジタル入出力、アナログ出力に加えてアナログ入力を行うためには外部 IC を利用する必要があります。ここでは I2C デバイスの ADS1015 を利用します。事前に I2C 設定を行っておいてください。

Python ライブラリを用いたサンプル
ADS1015 を扱うための専用ライブラリが Python で提供されています。
以下のコマンドでインストールします。
sudo pip install adafruit-ads1x15
以前は Adafruit-Raspberry-Pi-Python-Code レポジトリで提供されていましたが、管理が煩雑になったため分離されて pip での提供に変更になったようです。
Over time we found it difficult to manage so much code in a single repository, and couldn't easily put the code on Python's package index for simple installation. Now we've broken out all of the previous Python code into individual GitHub repositories, and we've loaded all of these repositories on the Python package index so they can be installed with pip.
回路図は以下の通りです。10k 可変抵抗で A/D 変換を試してみます。

sample.py (公式ページにもサンプルコードがあります)
#!/path/to/python
# -*- coding: utf-8 -*-
import Adafruit_ADS1x15
import time
CHANNEL = 0
GAIN = 1
adc = Adafruit_ADS1x15.ADS1015()
while True:
print(adc.read_adc(CHANNEL, gain=GAIN))
time.sleep(0.5)
GAIN の値は A0 端子に入力される電圧によって変更します。
- 2/3: 0.0V - 6.144V
- 1: 0.0V - 4.096V
- 2: 0.0V - 2.048V
- 4: 0.0V - 1.024V
- 8: 0.0V - 0.512V
- 16: 0.0V - 0.256V
上記設定における ADS1015 の分解能は 11bit (2048) です。3.3V のアナログ入力がなされた場合の値はおおよそ 2048*(3.3/4.096) = 1650 です。
他の言語で利用するための検討
残念ながら Python 以外の言語で I2C 通信を行うためのライブラリが充実していません。データシートをもとに i2cget と i2cset コマンドを実行する方法も考えられますが、仕様が複雑です。リアルタイム性が損なわれますが、例えば python スクリプトをコマンド化して、それを各言語のシステム関数で実行するという方法も考えられます。
adc.py
!/usr/bin/python
# -*- coding: utf-8 -*-
import Adafruit_ADS1x15
print(Adafruit_ADS1x15.ADS1015().read_adc(0, gain=1))
sample.rb
#!/usr/bin/ruby
# -*- coding: utf-8 -*-
while true do
system "./adc.py"
sleep 0.5
end
実行例
pi@raspberrypi:~ $ chmod +x adc.py
pi@raspberrypi:~ $ ruby sample.rb
0
179
539
963
1340
1615
1645
Pythonを使ったFlaskアプリ開発が得意
記事の執筆者にステッカーを贈る
有益な情報に対するお礼として、またはコメント欄における質問への返答に対するお礼として、 記事の読者は、執筆者に有料のステッカーを贈ることができます。
さらに詳しく →Feedbacks
ログインするとコメントを投稿できます。





