以前、M5StickCに防水タイプの温度センサ「DS18B20」をつなぎ、温度測定できることを確認しました(記事は こちら)。
このセンサは「1-Wire」という通信規格をつかっており、信号線にプルアップ抵抗をつなぐ必要があるのですが、この記事を読んだ方から「プルアップ抵抗なしで、温度センサとM5StickCのGROVEポートを直結できたらいいのに」というコメントをいただきました。
ここで使用しているのは単なるプルアップ抵抗です。プルアップ抵抗ならESP32(M5StickCで使われているマイコン)のGPIOにも内蔵されており、それを活用できれば外付け抵抗は不要になるのではないか?と考えました。
「OneWire」ライブラリを確認すると、中で「pinMode(pin, INPUT);」と定義されています。この情報を上書きするだけで抵抗をつながなくても動くようになるかもしれません。
早速試してみることにしました。
まずは以前の記事と全く同じスケッチ、全く同じ接続方法で動作確認しました。
#include <M5StickC.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS 33
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
void setup() {
M5.begin();
Serial.println("Dallas Temperature IC Control Library Demo");
sensors.begin();
}
void loop() {
Serial.print("Requesting temperatures...");
sensors.requestTemperatures(); // Send the command to get temperatures
Serial.println("DONE");
float tempC = sensors.getTempCByIndex(0);
if(tempC != DEVICE_DISCONNECTED_C) {
Serial.print("Temperature for the device 1 (index 0) is: ");
Serial.println(tempC);
} else {
Serial.println("Error: Could not read temperature data");
}
}

シリアルモニタには、温度情報がレポートされます。
Requesting temperatures...DONE
Temperature for the device 1 (index 0) is: 21.31
Requesting temperatures...DONE
Temperature for the device 1 (index 0) is: 21.31
Requesting temperatures...
:
次に、この回路から抵抗を取り外します。プログラムは変更しません。
すると、シリアルモニタに、温度データを取得できないというメッセージが表示されるようになりました。
Requesting temperatures...DONE
Error: Could not read temperature data
Requesting temperatures...DONE
Error: Could not read temperature data
Requesting temperatures...
:
さて、次はいよいよスケッチを変更します。といっても、setup内に「pinMode(ONE_WIRE_BUS, INPUT_PULLUP);」の1行を追加するだけです。
#include <M5StickC.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS 33
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
void setup() {
M5.begin();
Serial.println("Dallas Temperature IC Control Library Demo");
pinMode(ONE_WIRE_BUS, INPUT_PULLUP);
sensors.begin();
}
void loop() {
Serial.print("Requesting temperatures...");
sensors.requestTemperatures(); // Send the command to get temperatures
Serial.println("DONE");
float tempC = sensors.getTempCByIndex(0);
if(tempC != DEVICE_DISCONNECTED_C) {
Serial.print("Temperature for the device 1 (index 0) is: ");
Serial.println(tempC);
} else {
Serial.println("Error: Could not read temperature data");
}
}
先ほど、「M5StickC」-「DS18B20」間の接続からプルアップ抵抗を取り外しましたが、その状態でスケッチを上記のものに更新しました。
すると、以下のように、シリアルモニタに温度情報が問題なくレポートされるようになりました。
Requesting temperatures...DONE
Temperature for the device 1 (index 0) is: 21.31
Requesting temperatures...DONE
Temperature for the device 1 (index 0) is: 21.31
Requesting temperatures...
:
「DS18B20」を追加部品なしに「M5StickC」のGROVEポートに直結し、温度測定することができました。
これであれば、これまで以上にお気軽に「DS18B20」を活用できそうです。