Nano 33 BLE Senseでマルチセンサ・ペリフェラルを作る (2) 搭載センサHTS221①

 マイコン・ボードNano 33 BLE Senseには、次のようにいろいろなセンサが搭載されています。

 最初に、温湿度センサHTS221の温度と湿度を扱います。

温湿度センサHTS221のおもなスペック

  • 電源電圧 1.7~3.6V
  • 温度測定確度 ±0.5°C(15~40°C)
  • 湿度測定確度 ±3.5%RH(20~80%RH)
  • 湿度および温度出力データ 16ビット
  • インターフェース SPIおよびI2C

HTS221のライブラリ

 ライブラリ管理でHTS221を検索すると見つかります。インストールします。

 サンプル・スケッチからReadSensorを選び、コンパイル、書き込み、実行します。

スリムにする

 コメントを外し、必要な部分だけを残しました。

#include <Arduino_HTS221.h>

void setup() {
  Serial.begin(9600);
  while (!Serial);

  if (!HTS.begin()) {
    Serial.println("Failed to initialize humidity temperature sensor!");
    while (1);
  }
}

void loop() {
  float temperature = HTS.readTemperature();
  float humidity    = HTS.readHumidity();
  Serial.println(temperature);
  Serial.println(humidity);
  delay(1000);
}

関数にする

 スケッチの先頭で、温度と湿度の値はグローバル変数にします。readHTS221() 関数で温度と湿度を読み取ります。

#include <Arduino_HTS221.h>
float HTS221_temperature;
float HTS221_humidity;

void setup() {
  Serial.begin(9600);
  while (!Serial);

  if (!HTS.begin()) {
    Serial.println("Failed to initialize humidity temperature sensor!");
    while (1);
  }
}

void loop() {
  readHTS221();
  Serial.println(HTS221_temperature);
  Serial.println(HTS221_humidity);
  delay(1000);
}

void readHTS221() {
  HTS221_temperature = HTS.readTemperature();
  HTS221_humidity    = HTS.readHumidity();
}

 nano33sense.inoで保存します。

スケッチBatteryMonitor

 Arduino IDEのシリアルモニタのアイコンの下にある矢印アイコンをクリックし、新規タブを選びます。

 IDEの中央の帯付近に名前を入力するようにメッセージが出るので、nano33sense_Peripheralとしました。新規なエディタ画面が開きます。

 サンプルのArduinoBLE-Peripheralに入っているBatteryMonitorを開き、コメントを除いて貼り込みます。

 タブnano33senseのsetup()から、

if (!HTS.begin()) {
  Serial.println("Failed to initialize humidity temperature sensor!");
  while (1);
}

をコピーし、タブnano33sense_Peripheralのsetup()に貼り込みます。タブnano33senseのvoid setup()とloop()をコメントアウトします。つまり、残るのは、変数の宣言とreadHTS221() 関数だけです。

#include <Arduino_HTS221.h>
float HTS221_temperature;
float HTS221_humidity;

void readHTS221() {
  HTS221_temperature = HTS.readTemperature();
  HTS221_humidity    = HTS.readHumidity();
}

 タブnano33sense_PeripheralのupdateBatteryLevel()関数内で、バッテリ・レベルを作っている部分をreadHTS221() 関数の温度に変更します。

// int battery = analogRead(A0);
// int batteryLevel = map(battery, 0, 1023, 0, 100);
readHTS221();
int batteryLevel = int(HTS221_temperature);

 これで、コンパイル、書き込み、実行します。

 RSL10のモニタで観測しました。正しく温度は送られています。

温度のキャラに加えて湿度用キャラを追加する

 元のスケッチに湿度用にキャラとUUIDを追加するという強引な形でスケッチを更新し、温度と湿度を送れるように改造します。

 実行結果です。UUIDは、前回のSensorTagの温湿度センサHDC1000から流用しました。

 タブnano33sense_Peripheralの内容です。

#include <ArduinoBLE.h>

 // BLE Battery Service
BLEService batteryService("F000AA20-0451-4000-B000-000000000000");

// BLE Battery Level Characteristic
BLEUnsignedCharCharacteristic batteryLevelChar("F000AA21-0451-4000-B000-000000000000",  // standard 16-bit characteristic UUID
    BLERead | BLENotify); // remote clients will be able to get notifications if this characteristic changes

BLEUnsignedCharCharacteristic batteryLevel2Char("F000AA22-0451-4000-B000-000000000000",  // standard 16-bit characteristic UUID
    BLERead | BLENotify); // remote clients will be able to get notifications if this characteristic changes

int oldBatteryLevel = 0;  // last battery level reading from analog input
long previousMillis = 0;  // last time the battery level was checked, in ms

void setup() {
  Serial.begin(9600);    // initialize serial communication
  while (!Serial);

  pinMode(LED_BUILTIN, OUTPUT); // initialize the built-in LED pin to indicate when a central is connected

  // begin initialization
  if (!BLE.begin()) {
    Serial.println("starting BLE failed!");

    while (1);
  }
  
  if (!HTS.begin()) {
    Serial.println("Failed to initialize humidity temperature sensor!");
    while (1);
  }
  /* Set a local name for the BLE device
     This name will appear in advertising packets
     and can be used by remote devices to identify this BLE device
     The name can be changed but maybe be truncated based on space left in advertisement packet
  */
  BLE.setLocalName("BatteryMonitor2");
  BLE.setAdvertisedService(batteryService); // add the service UUID
  batteryService.addCharacteristic(batteryLevelChar); // add the battery level characteristic
  batteryService.addCharacteristic(batteryLevel2Char); // add the battery level characteristic
  BLE.addService(batteryService); // Add the battery service
  batteryLevelChar.writeValue(oldBatteryLevel); // set initial value for this characteristic
  batteryLevel2Char.writeValue(oldBatteryLevel); // set initial value for this characteristic
  /* Start advertising BLE.  It will start continuously transmitting BLE
     advertising packets and will be visible to remote BLE central devices
     until it receives a new connection */

  // start advertising
  BLE.advertise();

  Serial.println("Bluetooth device active, waiting for connections...");
}

void loop() {
  // wait for a BLE central
  BLEDevice central = BLE.central();

  // if a central is connected to the peripheral:
  if (central) {
    Serial.print("Connected to central: ");
    // print the central's BT address:
    Serial.println(central.address());
    // turn on the LED to indicate the connection:
    digitalWrite(LED_BUILTIN, HIGH);

    // check the battery level every 200ms
    // while the central is connected:
    while (central.connected()) {
      long currentMillis = millis();
      // if 200ms have passed, check the battery level:
      if (currentMillis - previousMillis >= 200) {
        previousMillis = currentMillis;
        updateBatteryLevel();
      }
    }
    // when the central disconnects, turn off the LED:
    digitalWrite(LED_BUILTIN, LOW);
    Serial.print("Disconnected from central: ");
    Serial.println(central.address());
  }
}

void updateBatteryLevel() {
  /* Read the current voltage level on the A0 analog input pin.
     This is used here to simulate the charge level of a battery.
  */
//  int battery = analogRead(A0);
//  int batteryLevel = map(battery, 0, 1023, 0, 100);
    readHTS221();
    int batteryLevel = int(HTS221_temperature);
    int batteryLevel2 = int(HTS221_humidity);
  if (batteryLevel != oldBatteryLevel) {      // if the battery level has changed
    Serial.print("Battery Level % is now: "); // print it
    Serial.println(batteryLevel);
    batteryLevelChar.writeValue(batteryLevel);  // and update the battery level characteristic
    batteryLevel2Char.writeValue(batteryLevel2);  // and update the battery level characteristic
    oldBatteryLevel = batteryLevel;           // save the level for next comparison
  }
}

 読みずらいので、次回、書き直します。また、データに変化があったときに最新データを送るNotifyの機能は動いていません。

前へ

Nano 33 BLE Senseでマルチセンサ・ペリフェラルを作る (1) BLEとは

次へ

Nano 33 BLE Senseでマルチセンサ・ペリフェラルを作る (3) 搭載センサHTS221②