2020年4月30日木曜日

M5Atomで『離席中』対策装置を作成

PCの無操作スクリーンロック、離席中ステータス表示などを回避する装置を作成する

概要

・M5AtomはPCからBluetoothマウスとして認識される

・以下の内部状態を持つ
 ・ペアリングモード
 ・待機モード
 ・自動動作モード

・ペアリングモード
 PCとのペアリングを待つ
 成功時は待機モードに遷移

・待機モード
 ユーザーのM5Atomボタン押し操作を待つ
 ボタンが押されたら自動動作モードに遷移

・自動動作モード
 マウスカーソルを常時動かし続ける
 ユーザーのM5Atomボタン押し操作を待つ
 ボタンが押されたら待機モードに遷移

作成方法

ソースコード(後述)をビルドしてM5Atomに書き込み

使用方法

初回のみペアリング操作が必要

ペアリング: 
 M5Atomを通電させてLEDが白色(ペアリングモード)になることを確認
 PCの設定からBluetooth機器の追加(ESP32 Bluetooth Mouse)を行う
 LEDが赤色(待機モード)になることを確認
 初回以降は通電後自動的にPCと接続される

動作の切り替え:
 LED赤色表示(待機モード)でM5Atomのボタンを押す
 LEDが緑色(自動動作モード)になることを確認
 マウスカーソルが自動的に動く
 再度ボタンを押すとLEDが赤色表示(待機モード)になりマウスカーソルは止まる

ソースコード解説

ESP32 Bluetooth Mouseライブラリ+M5AtomのButtonサンプルコード
loop()でマウスカーソルを動かす箇所は見栄えを良くしているだけでもっと簡単でよい

ソースコード


#include "M5Atom.h"
#include <BleMouse.h>

#define MAX_X 320
#define MAX_Y 240

int point_x = 0;
int point_y = 0;

int dir_x = 1;
int dir_y = 1;

int moveFlag = 0;

BleMouse bleMouse;

uint8_t DisBuff[2 + 5 * 5 * 3];

void setBuff(uint8_t Rdata, uint8_t Gdata, uint8_t Bdata)
{
    DisBuff[0] = 0x05;
    DisBuff[1] = 0x05;
    for (int i = 0; i < 25; i++)
    {
        DisBuff[2 + i * 3 + 0] = Rdata;
        DisBuff[2 + i * 3 + 1] = Gdata;
        DisBuff[2 + i * 3 + 2] = Bdata;
    }
}

void setup() {
  Serial.begin(115200);
  Serial.println("Starting BLE work!");
  bleMouse.begin();
  M5.begin(true, false, true);

  setBuff(0x10, 0x10, 0x10);
  M5.dis.displaybuff(DisBuff);
  while(1)
  {
    if(bleMouse.isConnected()) {
      Serial.println("Connect");
      setBuff(0x10, 0x00, 0x00);
      M5.dis.displaybuff(DisBuff);      
      break;      
    }
    delay(100);
    Serial.print(".");
  }  
}

void loop() {

    if (M5.Btn.wasPressed())
    {
      if(moveFlag == 0)
      {
        moveFlag = 1;
        setBuff(0x00, 0x10, 0x00);
      }
      else
      {
        moveFlag = 0;
        setBuff(0x10, 0x00, 0x00);
      }
      M5.dis.displaybuff(DisBuff);      
    }
    if(moveFlag == 1)
    {
      bleMouse.move(dir_x, dir_y);
      point_x += dir_x;
      if(point_x <= 0)
      {
        point_x = 0;
        dir_x = 1;
      }
      else if(MAX_X <= point_x)
      {
        point_x = MAX_X;
        dir_x = -1;
      }
      
      point_y += dir_y;
      if(point_y <= 0)
      {
        point_y = 0;
        dir_y = 1;
      }
      else if(MAX_Y <= point_y)
      {
        point_y = MAX_Y;
        dir_y = -1;
      }
    }
    delay(5);
    M5.update();  
  
}