.. note::
こんにちは、SunFounder Raspberry Pi & Arduino & ESP32 愛好者コミュニティ (Facebook) へようこそ!
Raspberry Pi、Arduino、ESP32 を仲間と共にさらに深く学びましょう。
**参加する理由**
- **専門サポート**: 購入後の問題や技術的課題をコミュニティとチームで解決
- **学びと共有**: ヒントや学習資料を交換し、技術力を向上
- **限定プレビュー**: 新製品情報や先行発表に早期アクセス
- **特別割引**: 新製品を特別価格で購入可能
- **イベントと景品企画**: 景品イベントや季節ごとのキャンペーンに参加
👉 一緒に探求し、ものづくりを楽しみましょう。[|link_sf_facebook|] をクリックして参加!
.. _2.2.2_py_pi5_mcp3008:
2.2.2 サーミスタ (MCP3008)
============================
.. note::
.. image:: ../img/mcp3008_and_adc0834.jpg
:width: 25%
:align: left
キットのバージョンに応じて **ADC0834** または **MCP3008** が含まれています。
お手持ちのバージョンに対応する章をご参照ください。
概要
----
フォトレジスタが光を検知するのと同様に、サーミスタは温度に応じて抵抗値が変化する部品です。
これを利用することで、例えば温度制御や高温警報などの機能を実現できます。
必要な部品
----------
このプロジェクトで必要な部品は以下の通りです。
.. image:: ../python_pi5/img/list2_2.2.2_thermistor.png
キット一式で購入すると便利です。リンクはこちら:
.. list-table::
:widths: 20 20 20
:header-rows: 1
* - 名称
- キット内数量
- リンク
* - Raphael Kit
- 337
- |link_Raphael_kit|
個別に購入することもできます。以下のリンクをご参照ください。
.. list-table::
:widths: 30 20
:header-rows: 1
* - 部品紹介
- 購入リンク
* - :ref:`cpn_gpio_extension_board`
- |link_gpio_board_buy|
* - :ref:`cpn_breadboard`
- |link_breadboard_buy|
* - :ref:`cpn_wires`
- |link_wires_buy|
* - :ref:`cpn_resistor`
- |link_resistor_buy|
* - :ref:`cpn_thermistor`
- |link_thermistor_buy|
* - :ref:`cpn_mcp3008`
- \-
回路図
------
.. .. image:: ../python_pi5/img/2.2.2_thermistor_schematic_1.png
.. list-table::
:widths: 30 30 30 30
:header-rows: 1
* - T-Board 名
- physical
- WiringPi
- BCM
* - SPICE0
- pin24
- 10
- 8
* - SPIMOSI
- pin19
- 12
- 10
* - SPIMISO
- pin21
- 13
- 9
* - SPISCLK
- pin23
- 14
- 11
.. image:: ../python_pi5/img/schematic_2.2.2_thermistor_mcp3008.png
実験手順
--------
**ステップ 1:** 回路を組み立てます。
.. image:: ../python_pi5/img/july24_2.2.2_thermistor_mcp3008.png
**ステップ 2:** SPI インターフェースを設定し、 ``spidev`` ライブラリをインストールします(詳細は :ref:`spi_configuration` を参照)。すでに設定済みの場合は省略可能です。
**ステップ 3:** コードがあるフォルダに移動します。
.. raw:: html
.. code-block::
cd ~/raphael-kit/python-pi5
**ステップ 4:** 実行します。
.. raw:: html
.. code-block::
sudo python3 2.2.2-2_Thermistor_zero.py
コードを実行すると、サーミスタが周囲温度を検知し、計算結果が画面に表示されます。
.. warning::
``RuntimeError: Cannot determine SOC peripheral base address`` エラーが表示された場合は :ref:`faq_soc` を参照してください。
コード
------
.. note::
以下のコードは **修正/リセット/コピー/実行/停止** が可能です。
その前に ``raphael-kit/python-pi5`` のソースコードパスに移動してください。変更後、直接実行して結果を確認できます。
.. raw:: html
.. code-block:: python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import spidev
import time
import math
# Initialize SPI for MCP3008 (Bus 0, CE0)
spi = spidev.SpiDev()
spi.open(0, 0) # Bus 0, Device 0 (CE0)
spi.max_speed_hz = 1000000 # 1 MHz
def read_adc(channel):
"""
Read analog value from MCP3008 channel (0–7)
"""
if channel < 0 or channel > 7:
return -1
# MCP3008 communication format
adc = spi.xfer2([1, (8 + channel) << 4, 0])
value = ((adc[1] & 0x03) << 8) | adc[2]
return value
try:
while True:
# Read analog value from CH0 of MCP3008
analogVal = read_adc(0)
# Convert to voltage (3.3V reference)
Vr = 3.3 * analogVal / 1023.0
# Calculate thermistor resistance
Rt = 10000.0 * Vr / (3.3 - Vr)
# Calculate temperature in Kelvin using the Steinhart–Hart approximation
tempK = 1.0 / (((math.log(Rt / 10000.0)) / 3950.0) + (1.0 / (273.15 + 25.0)))
# Convert to Celsius and Fahrenheit
Cel = tempK - 273.15
Fah = Cel * 1.8 + 32
# Print the temperature
print('Celsius: %.2f °C Fahrenheit: %.2f °F' % (Cel, Fah))
# Wait before next reading
time.sleep(0.2)
except KeyboardInterrupt:
spi.close()
コード解説
----------
1. ``spidev`` モジュールで MCP3008 と通信し、 ``time`` モジュールで待機処理を、 ``math`` モジュールで温度計算に必要な対数計算を行います。
.. code-block:: python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import spidev
import time
import math
2. MCP3008 をバス 0、デバイス 0 (CE0) で初期化し、SPI クロック速度を 1 MHz に設定します。
.. code-block:: python
# Initialize SPI for MCP3008 (Bus 0, CE0)
spi = spidev.SpiDev()
spi.open(0, 0) # Bus 0, Device 0 (CE0)
spi.max_speed_hz = 1000000 # 1 MHz
3. 指定した MCP3008 チャンネル (0~7) からアナログ値を読み取る関数 ``read_adc()`` を定義しています。SPI を使用し、10 ビット整数 (0~1023) を返します。
.. code-block:: python
def read_adc(channel):
"""
Read analog value from MCP3008 channel (0–7)
"""
if channel < 0 or channel > 7:
return -1
# MCP3008 communication format
adc = spi.xfer2([1, (8 + channel) << 4, 0])
value = ((adc[1] & 0x03) << 8) | adc[2]
return value
4. 無限ループで CH0 のサーミスタ値を取得し、電圧 (3.3V 基準) に変換、その後抵抗値に変換します。
ステインハート・ハート式を使用して絶対温度 (K) を計算し、摂氏 (°C) および華氏 (°F) に変換して表示します。
0.2 秒ごとに更新します。
.. code-block:: python
try:
while True:
# Read analog value from CH0 of MCP3008
analogVal = read_adc(0)
# Convert to voltage (3.3V reference)
Vr = 3.3 * analogVal / 1023.0
# Calculate thermistor resistance
Rt = 10000.0 * Vr / (3.3 - Vr)
# Calculate temperature in Kelvin using the Steinhart–Hart approximation
tempK = 1.0 / (((math.log(Rt / 10000.0)) / 3950.0) + (1.0 / (273.15 + 25.0)))
# Convert to Celsius and Fahrenheit
Cel = tempK - 273.15
Fah = Cel * 1.8 + 32
# Print the temperature
print('Celsius: %.2f °C Fahrenheit: %.2f °F' % (Cel, Fah))
# Wait before next reading
time.sleep(0.2)
5. ``KeyboardInterrupt`` (Ctrl+C) を検知するとプログラムを終了し、SPI 接続を閉じてリソースを解放します。
.. code-block:: python
except KeyboardInterrupt:
spi.close()