3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

MongooseOS + mjs で I2C 気温センサを読み取る

Posted at

Mongoose js の I2C ライブラリの使い方で手間取ったのでメモを残しておきます。
SHT31 というセンサーを使い、気温と湿度を取ります。

Mongoose OS + mjs の git 管理開発環境構築 - Qiita で作った環境を使います。

fs/init.js

load("api_config.js");
load("api_mqtt.js");
load("api_net.js");
load("api_sys.js");
load("api_timer.js");
load("api_i2c.js");

let address = 0x44;
let bus = I2C.get_default();

let get_temps = function() {
	let d = "\x2C\x06";
	I2C.write(bus, address, d, d.length, true);
	Sys.usleep(1000);

	let data = I2C.read(bus, address, 6, true);

	print(data);

	let temp = data.at(0) * 256 + data.at(1);
	let cTemp = -45 + 175 * temp / 65535.0;
	let fTemp = -49 + 315 * temp / 65535.0;
	let humidity = 100 * (data.at(3) * 256 + data.at(4)) / 65535.0;

	return [temp, cTemp, fTemp, humidity];
};

Timer.set(
	1000 * 5,
	true /* repeat */,
	function() {
		let res = get_temps();
		print("t:");
		print(res[1]);
		print("h:");
		print(res[3]);
		// MQTT.pub('home/livingroom/brightness', JSON.stringify(lux), 0);
	},
	null
);

SHT31 のデータシートはこれです。http://akizukidenshi.com/download/ds/sensirion/Sensirion_Humidity_Sensors_SHT3x_DIS_Datasheet_V3_J.pdf

つまづいた所

公式ライブラリの api_i2c.js のドキュメント
コード: https://github.com/mongoose-os-libs/i2c/blob/master/mjs_fs/api_i2c.js

  1. I2C.write の使い方
  2. sleep が必要
  3. I2C.read の使い方
I2C.write(bus, address, "\x2C\x06", 2, true);
Sys.usleep(1000);
let data = I2C.read(bus, address, 6, true);

Python と比較

bus.write_i2c_block_data(address, 0x2C, [0x06])
time.sleep(0.5)
data = bus.read_i2c_block_data(address, 0x00, 6)

address は 0x44 です。
buf はデータシートにあるように指定します。
6byte 読めます。

暫定版.png

参考

ControlEverythingCommunity/SHT31: Humidity and Temperature Sensor
Python や Arduino での実装サンプルなど↑

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?