以前、Arduinoのアナログ入力にサーミスタをつなぎ、温度計にして遊んだ。最近はLCDディスプレイに温度を表示してみたり、なかなか面白い。
一方、Raspberry PiはWebによくなじむ。ApacheもPHPも走る。
それで、先週宮城大学小島研究室のサイトで公開しておられるADCアクセスのためのソースコードを拝借して遊んだが、これを使ってWeb温度計にしてみた。
まず、ブレッドボードにAD変換ICのMCP3208と、サーミスタ、分圧用の抵抗1kΩを置き、適切に配線する。これには、以前Arduinoで遊ぶために買った「Seeedstudio Arduino Sidekick Basic Kit」に入っていたMF11-503Kというサーミスタをそのまま使う。
それから、C++でこんなプログラムを書く。先週も書いたが、宮城大学小島研究室のサイトで公開しておられるコードは、Raspberry Pi 1では何の支障もなく動くが、Raspberry Pi 2 Model Bではそのままでは動かない。一部の型キャストなどを変更する必要がある。それについては先週のエントリで記してある。
//
// tempMesure.cpp
// 佐藤俊夫
// Sun Sep 6 13:57:53 JST 2015
// サーミスタMF11-503Kと1kΩ抵抗を直列につなぎ、3.3Vを印加して、
// その間から分圧をとって温度を測る。
// 宮城大学小島研究室でウェブ公開しておられるソースコードを拝借した。
// コンパイル
// cc -lm tempMesure.cpp raspSPI.o raspADC.o -o tempMesure
//
#include <stdio.h>
#include <math.h>
#include "raspADC.h"
#define ADC_CHIP ADC_3208
float tempMesure(int srcVal);
int main() {
ADC adc;
adc.init("/dev/spidev0.1", ADC_CHIP);
printf("%2.2f\n", tempMesure(adc.get(0)));
}
float tempMesure(int srcVal){
const float B = 4350.0, Ta = 25.0, Rt0 = 50000.0; // MF11-503Kスペックシート記載
const float K = 273.15; // 熱力学温度の定数
const float v0 = 3.3, r0 = 1000.0; // Arduino +5Vと電流調整抵抗1kΩ
const int resolution = 4096; // アナログ入力の分解能
float vt = 0.0, rt = 0.0;
vt = srcVal * (v0 / (resolution - 1));
rt = (v0 * r0 - vt * r0) / vt;
return(1.0 / (log(rt / Rt0) / B + 1.0 / (Ta + K)) - K);
}
これは単に、サーミスタで計った現在の温度を標準出力に書くだけだ。
これを「popen();」で開けば、PHPで読める。簡単である。
<html>
<head>
<meta name="Editor" content="vim">
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<link rel="icon" href="favicon.ico" type="image/x-icon" />
<link rel="Shortcut Icon" type="image/x-icon" href="favicon.ico" />
<title>PHPで温度計</title>
<meta http-equiv="Keyword" content="佐藤俊夫, 佐藤, 俊夫, SATOTOSHIO, SatoToshio, sato, toshio, Raspberry Pi, Raspberry Pi 2 Model B">
</head>
<body bgcolor="#888888">
<body>
<center>
<h1><img src="raspberry_pi.png" width="50px" align="middle"/>Raspberry Pi + PHPで温度計</h1>
<hr>
</center>
<?
ini_set( 'display_errors', 1 );
$process = popen("sudo /home/toshio/SPI_ADC/tempMesure", "r");
$temp = fgets($process);
?>
<center>
<table border=1 width="120px">
<tr> <th>0</th><th>10</th> <th>20</th> <th>30</th> <th>40</th> <th>50</th> <th>60</th></tr>
<tr><td colspan = 7>
<table>
<tr>
<td bgcolor="red" width="<?print $temp * 2?>px"><?print $temp?>℃</td&t;</tr></table>
</tr>
</table>
</td></tr></tr></table>
</center>
</body>
</html>
テーブルの幅を温度計のアルコール柱に見立てて、赤い帯で表すようにしてみた。
Arduinoでも同じようなことはできるが、Arduinoで難しいのは、こういうふうに、無駄に画像を配置したり、少し分量の多いHTMLを書いたりすることだ。だが、こんなことはRaspberry Piには造作もなくできてしまう。
反面、Arduinoはアナログ入力が直接可能だが、Raspberry Piで同じことをしようとすると、アナログ入力にAD変換ICを準備し、これとの通信にもいろいろと研究の上で取り組む必要がある。簡単で刺激的な目的のために少しプロトタイピングをしてみようと考えている多くのクリエイターがなしうるところではない。
入門書籍「Raspberry Piをはじめよう」にもそうしたことが少し書かれてある。