M5Stack用ジョイスティックユニットを使ってみた

今回は以下のジョイスティックを使ってみようと思います。

M5Stack用ジョイスティックユニット [U024]www.switch-science.com

 

M5Stack用と書いてありますが、私のPCではM5Stackが認識されなかったためM5Atomを使用しました。

※認識されないときはいろいろドライバを入れる必要があるようですが、結局わからずじまいでした。

dev.classmethod.jp

 

M5Atomをに変えたことにより使用することができました。

ただ、M5Atomのスケッチ例のJOYSTICKはサンプルにもかかわらず、動かなかったため、少し修正を加えました。

プログラムは以下のようにしました。


    /*
*******************************************************************************
* Copyright (c) 2021 by M5Stack
*                  Equipped with Atom-Lite/Matrix sample source code
*                          配套  Atom-Lite/Matrix 示例源代码
* Visit the website for more information:https://docs.m5stack.com/en/unit/joystick
* 获取更多资料请访问:https://docs.m5stack.com/zh_CN/unit/joystick
*
* describe: JOYSTICK.
* date:2021/8/30
*******************************************************************************
  Please connect to Port,Read JOYSTICK Unit X, Y axis offset data and button status
  请连接端口,读取操纵杆单位X, Y轴偏移数据和按钮状态
*/

#include M5Atom.h

#define JOY_ADDR 0x52 //define Joystick I2C address.  定义摇杆的I2C地址

void setup() {
 M5.begin(true, false, true);
  //M5.begin();//ここを変えました
  Serial.begin(115200);
  Wire.begin(26,32);
}

char data[100];
void loop() {
  static uint8_t x_data,y_data,button_data;
  Wire.requestFrom(JOY_ADDR, 3);  //Request 3 bytes from the slave device.  向从设备请求3个字节
  if (Wire.available()) { //If data is received.  如果接收到数据
    x_data = Wire.read();
    y_data = Wire.read();
    button_data = Wire.read();
    sprintf(data, "x:%d y:%d button:%d\n", x_data, y_data, button_data);
    Serial.print(data);

    Serial.printf("x:%04d y:%04d button:%d\n", x_data, y_data, button_data);
  }
  delay(200);
}

--------------------------------------------------------------------------------------

ちなみに、Arduino IDEでは以上のファイルをAtomに書き込むことで動きますが、VScodeのPlatformIOを使用している人は少し手間が必要(ライブラリのダウンロードなど)です。

何をすればよいのかというと、

  1. main.cppの一番上に#include Arduino.hを追加します
  2. 以下のアイコンをクリックしてからLibraliesを選択し、M5AtomライブラリとFastLEDライブラリ(なんで必要かわからん)をプロジェクトに追加します
  3. シリアルモニタのbps値をそろえるためにmonitor_speed = 115200platformio.iniの一番下に記述します。

Platform IO

これで書き込むといけました。