LoginSignup
0
1

More than 3 years have passed since last update.

スイッチを押しているとき、加速度の値をBluetoothで送信する

Posted at

※この記事は、「LSM9DS1で加速度の値をシリアルにプリントする」を前提としています。

ジェスチャーゲームを目標としていますので、

  1. 無線通信できること
  2. 動作の切り取りをすること

が不可欠です。
動作の切り取りは閾値を指定してやることで解決できますが、今回はWiiのボウリングを見習ってボタン(スイッチ)で切り取りたいと思います。
スイッチを押し続けている間の動きをジェスチャーとして認識します。

回路

こんな感じ↓

image.png

コード

acc_ble.ino
#include <SparkFunLSM9DS1.h>
#include "BluetoothSerial.h"

#define LSM9DS1_M 0x1E
#define LSM9DS1_AG 0x6B
#define SW_PIN 7 //pin番号を指定する

LSM9DS1 imu;
BluetoothSerial SerialBT;

float x,y,z;
uint16_t connectionState = 0;

void setup()
{
  Serial.begin(115200);
  SerialBT.begin("ESP32"); //Bluetoothの名前を指定
  pinMode(SW_PIN, INPUT);

  imu.settings.device.commInterface = IMU_MODE_I2C;
  imu.settings.device.mAddress = LSM9DS1_M;
  imu.settings.device.agAddress = LSM9DS1_AG;
  if (connectionState == 0)
  {
    connectionState = imu.begin();
    while (connectionState == 0)
    {
      Serial.println("Failed to communicate with LSM9DS1.");
      Serial.println("Double-check wiring.");
      Serial.println("Default settings in this sketch will "
                     "work for an out of the box LSM9DS1 "
                     "Breakout, but may need to be modified "
                     "if the board jumpers are.");
      Serial.print("Connection Status: ");
      Serial.println(imu.begin());
      delay(1000);
      connectionState = imu.begin();
      Serial.println("------------------------------------------------------\n");
    }if(connectionState!=1){
      Serial.print("connectionState: ");
      Serial.println(connectionState);
    }
  }
}


void loop()
{
  imu.readAccel();
  x=imu.calcAccel(imu.ax)*10;
  y=imu.calcAccel(imu.ay)*10;
  z=imu.calcAccel(imu.az)*10;
  if(digitalRead(SW_PIN) == 1){ //スイッチが押されたら1、離すと0
    SerialBT.print("x=");
    SerialBT.print(x);
    SerialBT.print(", y=");
    SerialBT.print(y);
    SerialBT.print(", z=");
    SerialBT.println(z);
  }
  delay(500);
}

Bluetooth接続

書き込みが終了すると、ESP32はBluetooth接続を待機している状態になります。
PC側で接続してあげましょう。

  1. "設定" → "デバイス" → "Bluetoothとその他のデバイス"
  2. 上部の "Bluetoothまたはその他のデバイスを追加する" をクリック
  3. "Bluetooth" をクリックして "ESP32" を探してクリック
  4. 一覧に "ESP32 ペアリング済み" と出たら接続完了

完了すれば、PCとは切り離して、モバイルバッテリー等の電源に繋がっていれば大丈夫です。

受信した値を見る

方法はいくつかありますが、せっかくArduino IDEを使っていますのでそちらのシリアルモニタ(虫眼鏡のアイコン)で見てみましょう。
先ほど書き込んだポートのままになっていますので、"ツール" → "シリアルポート"でBluetoothのポート(さっきまではなかったポート)を探して変更しましょう。

以上です!
何か分からないことがあれば質問どうぞ!

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