Arduino入門

2. デバイス&サンプル

5. 拡張モジュール&サンプル

アクセサリー

6. アプリケーション

Unit 4EncoderMotor Driver Arduino チュートリアル

1. 準備

  • 環境設定:Arduino IDE 入門ガイドを参照して IDE をインストールし、使用する開発ボードに対応したボードパッケージとドライバーライブラリをインストールしてください。
  • 使用するライブラリ:
  • 使用するハードウェア:
    • CoreS3
    • Unit 4EncoderMotor Driver
    • 6 線式エンコーダー付きギヤードモーター × 4(M+ / M- / GND / 5V / EN_B / EN_A)
    • 外部 DC 6~12V 電源

2. 注意事項

ピン互換性
ホスト機器によってピン配置が異なります。M5Stack 公式のピン互換表を参照し、実際の接続に合わせてサンプルプログラムを変更してください。

3. サンプルプログラム

  • このチュートリアルでは、CoreS3 と Unit 4EncoderMotor Driver を使用して 4 チャンネルのエンコーダー付きモーターを制御します。ユニットは I2C 通信を使用し、接続ピンは G2 (SDA) と G1 (SCL) です。ユニットの 2 つの HY2.0-4P インターフェースは内部で接続されているため、どちらかをホストに接続し、もう一方に他の I2C デバイスを追加できます。
  • 以下では、ドライバーユニットが対応する PWM モード(開ループ速度制御)、速度モード(速度ループ)、位置モード(位置ループ)の各サンプルに加え、ソフトスタート/ソフトストップと RGB インジケーターのサンプルを紹介します。
  • すべてのサンプルで、ドライバーライブラリの M5UnitEncoderMotor クラスを使用し、コンストラクターに製品セレクター M5Unit_4EncoderMotor_Driver(デフォルトアドレス 0x24、4 チャンネル)を渡します。ドライバーライブラリは #include <M5Unit-EncoderMotor-Driver.h> で読み込みます。画面表示には、上記の M5Unified と M5GFX ライブラリも必要です。

3.1 PWM モード(4 チャンネル開ループ速度制御)

cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
#include <M5Unified.h>
#include <M5Unit-EncoderMotor-Driver.h>

// Product selector sets the default address and channel count:
// U232 = 0x2F (1 channel), U233 = 0x24 (4 channels)
M5UnitEncoderMotor motors(M5Unit_4EncoderMotor_Driver);

// Draw into an offscreen canvas so a full screen refresh does not flicker
M5Canvas canvas(&M5.Display);

constexpr int8_t I2C_SDA_PIN     = 2;  // CoreS3 PORT.A
constexpr int8_t I2C_SCL_PIN     = 1;
constexpr uint32_t I2C_FREQUENCY = 400000;
constexpr int8_t PWM_DUTY        = 100;   // -127 ~ 127
constexpr uint32_t RUN_MS        = 3000;
constexpr uint32_t STEP_MS       = 200;

void halt(const char *message)
{
    Serial.println(message);
    while (true) {
        delay(1000);
    }
}

// Center the status screen and mix three font sizes so the key value stands out.
void showScreen(const char *title, const char *value, const char *detail1, const char *detail2)
{
    canvas.fillScreen(TFT_BLACK);
    canvas.setTextDatum(middle_center);

    canvas.setFont(&fonts::DejaVu18);
    canvas.setTextColor(TFT_LIGHTGREY);
    canvas.drawString(title, canvas.width() / 2, 32);

    canvas.setFont(&fonts::DejaVu40);
    canvas.setTextColor(TFT_WHITE);
    canvas.drawString(value, canvas.width() / 2, 112);

    canvas.setFont(&fonts::DejaVu12);
    canvas.setTextColor(TFT_LIGHTGREY);
    if (detail1 && detail1[0]) {
        canvas.drawString(detail1, canvas.width() / 2, 176);
    }
    if (detail2 && detail2[0]) {
        canvas.drawString(detail2, canvas.width() / 2, 204);
    }

    canvas.pushSprite(0, 0);
}

void drawStatus(const char *state, int8_t duty)
{
    int8_t speed[4] = {0, 0, 0, 0};
    for (uint8_t channel = 0; channel < motors.motorCount() && channel < 4; ++channel) {
        motors.getSpeed(speed[channel], channel);
    }

    char value[16];
    char detail1[48];
    char detail2[48];
    snprintf(value, sizeof(value), "%+d", speed[0]);
    snprintf(detail1, sizeof(detail1), "%s   duty %+d", state, duty);
    snprintf(detail2, sizeof(detail2), "M2 %+d   M3 %+d   M4 %+d", speed[1], speed[2], speed[3]);
    showScreen("PWM", value, detail1, detail2);
}

// Apply the duty cycle to every channel and keep reporting back
void holdDuty(const char *state, int8_t duty, uint32_t duration_ms)
{
    for (uint8_t channel = 0; channel < motors.motorCount(); ++channel) {
        if (!motors.setPWMDuty(duty, channel)) {
            halt("Failed to set PWM duty.");
        }
    }
    for (uint32_t elapsed = 0; elapsed < duration_ms; elapsed += STEP_MS) {
        drawStatus(state, duty);
        Serial.printf("%s duty=%+d", state, duty);
        for (uint8_t channel = 0; channel < motors.motorCount(); ++channel) {
            int8_t speed = 0;
            int32_t encoder = 0;
            motors.getSpeed(speed, channel);
            motors.getEncoder(encoder, channel);
            Serial.printf(" M%u[speed=%+d encoder=%ld]", channel + 1, speed, static_cast<long>(encoder));
        }
        Serial.println();
        delay(STEP_MS);
    }
}

void setup()
{
    auto cfg = M5.config();
    cfg.output_power = true;
    M5.begin(cfg);
    canvas.createSprite(M5.Display.width(), M5.Display.height());
    Serial.begin(115200);

    while (!motors.begin(&Wire, 0, I2C_SDA_PIN, I2C_SCL_PIN, I2C_FREQUENCY)) {
        Serial.println("Unit 4EncoderMotor Driver not found");
        delay(1000);
    }
    delay(100);  // give the unit time to finish the previous write
    for (uint8_t channel = 0; channel < motors.motorCount(); ++channel) {
        // Soft start is saved in the unit flash; turn it off so this demo runs without a ramp
        if (!motors.setSoftStartStop(false, channel)) {
            halt("Failed to disable soft start / stop.");
        }
        if (!motors.setMotorMode(M5_UNIT_ENCODER_MOTOR_MODE_NORMAL, channel) || !motors.setPWMDuty(0, channel)) {
            halt("Failed to initialise PWM mode.");
        }
    }
    Serial.println("Unit 4EncoderMotor Driver ready");
}

void loop()
{
    holdDuty("forward", PWM_DUTY, RUN_MS);
    holdDuty("coast", 0, 1000);
    holdDuty("reverse", -PWM_DUTY, RUN_MS);
    holdDuty("coast", 0, 1000);
}

製品セレクター M5Unit_4EncoderMotor_Driver を指定して M5UnitEncoderMotor オブジェクトを作成します。begin() のアドレスに 0 を渡すとデフォルトの 0x24 が使われ、motorCount() はチャンネル数 4 を返します。setPWMDuty()、getSpeed()、getEncoder() など、チャンネル引数を持つ API は 0 ~ 3 でチャンネルを指定し、省略時は 0 が使われます。ループでは 4 台ともデューティ値 100 で 3 秒間正転し、ゼロにして 1 秒間惰性回転した後、-100 で 3 秒間逆転します。

シリアル出力例:

Unit 4EncoderMotor Driver ready
forward duty=+100 M1[speed=+16 encoder=804] M2[speed=+16 encoder=806] M3[speed=+16 encoder=801] M4[speed=+16 encoder=803]
coast duty=+0 M1[speed=+6 encoder=1512] M2[speed=+6 encoder=1515] M3[speed=+6 encoder=1509] M4[speed=+6 encoder=1511]
reverse duty=-100 M1[speed=-15 encoder=1180] M2[speed=-15 encoder=1177] M3[speed=-15 encoder=1182] M4[speed=-15 encoder=1179]

3.2 速度モード(4 チャンネル同期)

cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
#include <M5Unified.h>
#include <M5Unit-EncoderMotor-Driver.h>

// Product selector sets the default address and channel count:
// U232 = 0x2F (1 channel), U233 = 0x24 (4 channels)
M5UnitEncoderMotor motors(M5Unit_4EncoderMotor_Driver);

// Draw into an offscreen canvas so a full screen refresh does not flicker
M5Canvas canvas(&M5.Display);

constexpr int8_t I2C_SDA_PIN     = 2;  // CoreS3 PORT.A
constexpr int8_t I2C_SCL_PIN     = 1;
constexpr uint32_t I2C_FREQUENCY = 400000;
constexpr int8_t TARGET_SPEED    = 15;
constexpr M5UnitEncoderMotorPID SPEED_PID = {10, 1, 15};  // Default speed loop P / I / D
constexpr uint32_t RUN_MS        = 5000;
constexpr uint32_t STEP_MS       = 200;

void halt(const char *message)
{
    Serial.println(message);
    while (true) {
        delay(1000);
    }
}

// Center the status screen and mix three font sizes so the key value stands out.
void showScreen(const char *title, const char *value, const char *detail1, const char *detail2)
{
    canvas.fillScreen(TFT_BLACK);
    canvas.setTextDatum(middle_center);

    canvas.setFont(&fonts::DejaVu18);
    canvas.setTextColor(TFT_LIGHTGREY);
    canvas.drawString(title, canvas.width() / 2, 32);

    canvas.setFont(&fonts::DejaVu40);
    canvas.setTextColor(TFT_WHITE);
    canvas.drawString(value, canvas.width() / 2, 112);

    canvas.setFont(&fonts::DejaVu12);
    canvas.setTextColor(TFT_LIGHTGREY);
    if (detail1 && detail1[0]) {
        canvas.drawString(detail1, canvas.width() / 2, 176);
    }
    if (detail2 && detail2[0]) {
        canvas.drawString(detail2, canvas.width() / 2, 204);
    }

    canvas.pushSprite(0, 0);
}

void drawStatus(const char *state, int8_t target)
{
    int8_t speed[4] = {0, 0, 0, 0};
    for (uint8_t channel = 0; channel < motors.motorCount() && channel < 4; ++channel) {
        motors.getSpeed(speed[channel], channel);
    }

    char value[16];
    char detail1[48];
    char detail2[48];
    snprintf(value, sizeof(value), "%+d", speed[0]);
    snprintf(detail1, sizeof(detail1), "%s   target %+d", state, target);
    snprintf(detail2, sizeof(detail2), "M2 %+d   M3 %+d   M4 %+d", speed[1], speed[2], speed[3]);
    showScreen("SPEED", value, detail1, detail2);
}

// Hold the same target speed on all channels and print the closed loop response
void holdSpeed(const char *state, int8_t target, uint32_t duration_ms)
{
    for (uint8_t channel = 0; channel < motors.motorCount(); ++channel) {
        if (!motors.runSpeed(target, SPEED_PID, channel)) {
            halt("Failed to run in Speed mode.");
        }
    }
    for (uint32_t elapsed = 0; elapsed < duration_ms; elapsed += STEP_MS) {
        drawStatus(state, target);
        Serial.printf("%s target=%+d", state, target);
        for (uint8_t channel = 0; channel < motors.motorCount(); ++channel) {
            int8_t speed = 0;
            int8_t duty = 0;
            motors.getSpeed(speed, channel);
            motors.getPWMDuty(duty, channel);
            Serial.printf(" M%u[measured=%+d duty=%+d]", channel + 1, speed, duty);
        }
        Serial.println();
        delay(STEP_MS);
    }
}

void setup()
{
    auto cfg = M5.config();
    cfg.output_power = true;
    M5.begin(cfg);
    canvas.createSprite(M5.Display.width(), M5.Display.height());
    Serial.begin(115200);

    while (!motors.begin(&Wire, 0, I2C_SDA_PIN, I2C_SCL_PIN, I2C_FREQUENCY)) {
        Serial.println("Unit 4EncoderMotor Driver not found");
        delay(1000);
    }
    delay(100);  // give the unit time to finish the previous write
    for (uint8_t channel = 0; channel < motors.motorCount(); ++channel) {
        // Soft start is saved in the unit flash; turn it off so this demo runs without a ramp
        if (!motors.setSoftStartStop(false, channel)) {
            halt("Failed to disable soft start / stop.");
        }
        if (!motors.setMotorMode(M5_UNIT_ENCODER_MOTOR_MODE_NORMAL, channel) || !motors.setPWMDuty(0, channel)) {
            halt("Failed to initialise Speed mode.");
        }
    }
    Serial.println("Unit 4EncoderMotor Driver ready");
}

void loop()
{
    holdSpeed("run", TARGET_SPEED, RUN_MS);
    holdSpeed("stop", 0, 2000);
}

各チャンネルで runSpeed(15, SPEED_PID, channel) を呼び出します。SPEED_PID = {10, 1, 15} はファームウェアのデフォルト速度ループパラメーターで、目標値 15 の単位は 20 ms あたりのエンコーダーカウント増分です。ループでは 200 ms ごとに 4 チャンネルを順に読み取り、目標値、実測値、デューティ値を出力します。

シリアル出力例:

Unit 4EncoderMotor Driver ready
run target=+15 M1[measured=+15 duty=+54] M2[measured=+15 duty=+55] M3[measured=+14 duty=+56] M4[measured=+15 duty=+54]
stop target=+0 M1[measured=+0 duty=+0] M2[measured=+0 duty=+0] M3[measured=+0 duty=+0] M4[measured=+0 duty=+0]

3.3 位置モード(4 チャンネル同期)

cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
#include <M5Unified.h>
#include <M5Unit-EncoderMotor-Driver.h>

// Product selector sets the default address and channel count:
// U232 = 0x2F (1 channel), U233 = 0x24 (4 channels)
M5UnitEncoderMotor motors(M5Unit_4EncoderMotor_Driver);

// Draw into an offscreen canvas so a full screen refresh does not flicker
M5Canvas canvas(&M5.Display);

constexpr int8_t I2C_SDA_PIN     = 2;  // CoreS3 PORT.A
constexpr int8_t I2C_SCL_PIN     = 1;
constexpr uint32_t I2C_FREQUENCY = 400000;
constexpr int32_t TARGET_POSITION = 1320;  // One output revolution
constexpr int8_t MAX_SPEED        = 100;    // Position loop output limit
constexpr M5UnitEncoderMotorPID POSITION_PID = {1, 1, 17};  // Default position loop P / I / D
constexpr uint32_t TIMEOUT_MS     = 8000;
constexpr uint32_t STEP_MS        = 200;

void halt(const char *message)
{
    Serial.println(message);
    while (true) {
        delay(1000);
    }
}

// Center the status screen and mix three font sizes so the key value stands out.
void showScreen(const char *title, const char *value, const char *detail1, const char *detail2)
{
    canvas.fillScreen(TFT_BLACK);
    canvas.setTextDatum(middle_center);

    canvas.setFont(&fonts::DejaVu18);
    canvas.setTextColor(TFT_LIGHTGREY);
    canvas.drawString(title, canvas.width() / 2, 32);

    canvas.setFont(&fonts::DejaVu40);
    canvas.setTextColor(TFT_WHITE);
    canvas.drawString(value, canvas.width() / 2, 112);

    canvas.setFont(&fonts::DejaVu12);
    canvas.setTextColor(TFT_LIGHTGREY);
    if (detail1 && detail1[0]) {
        canvas.drawString(detail1, canvas.width() / 2, 176);
    }
    if (detail2 && detail2[0]) {
        canvas.drawString(detail2, canvas.width() / 2, 204);
    }

    canvas.pushSprite(0, 0);
}

void drawStatus(int32_t target)
{
    int32_t encoder[4] = {0, 0, 0, 0};
    for (uint8_t channel = 0; channel < motors.motorCount() && channel < 4; ++channel) {
        motors.getEncoder(encoder[channel], channel);
    }

    char value[16];
    char detail1[48];
    char detail2[48];
    snprintf(value, sizeof(value), "%ld", static_cast<long>(encoder[0]));
    snprintf(detail1, sizeof(detail1), "target %ld", static_cast<long>(target));
    snprintf(detail2, sizeof(detail2), "M2 %ld   M3 %ld   M4 %ld", static_cast<long>(encoder[1]),
             static_cast<long>(encoder[2]), static_cast<long>(encoder[3]));
    showScreen("POSITION", value, detail1, detail2);
}

// Move all channels to the target position and wait until they arrive
void moveTo(int32_t target, uint32_t timeout_ms)
{
    for (uint8_t channel = 0; channel < motors.motorCount(); ++channel) {
        if (!motors.runPosition(target, MAX_SPEED, POSITION_PID, channel)) {
            halt("Failed to run in Position mode.");
        }
    }
    for (uint32_t elapsed = 0; elapsed < timeout_ms; elapsed += STEP_MS) {
        drawStatus(target);
        bool reached = true;
        Serial.printf("target=%ld", static_cast<long>(target));
        for (uint8_t channel = 0; channel < motors.motorCount(); ++channel) {
            int32_t encoder = 0;
            motors.getEncoder(encoder, channel);
            if (abs(target - encoder) > 10) {
                reached = false;
            }
            Serial.printf(" M%u[encoder=%ld]", channel + 1, static_cast<long>(encoder));
        }
        Serial.println();
        if (reached) {
            Serial.println("position reached");
            return;
        }
        delay(STEP_MS);
    }
    Serial.println("position timeout");
}

void setup()
{
    auto cfg = M5.config();
    cfg.output_power = true;
    M5.begin(cfg);
    canvas.createSprite(M5.Display.width(), M5.Display.height());
    Serial.begin(115200);

    while (!motors.begin(&Wire, 0, I2C_SDA_PIN, I2C_SCL_PIN, I2C_FREQUENCY)) {
        Serial.println("Unit 4EncoderMotor Driver not found");
        delay(1000);
    }
    delay(100);  // give the unit time to finish the previous write
    for (uint8_t channel = 0; channel < motors.motorCount(); ++channel) {
        // Soft start is saved in the unit flash; turn it off so this demo runs without a ramp
        if (!motors.setSoftStartStop(false, channel)) {
            halt("Failed to disable soft start / stop.");
        }
        if (!motors.setMotorMode(M5_UNIT_ENCODER_MOTOR_MODE_NORMAL, channel) || !motors.setPWMDuty(0, channel) ||
            !motors.clearEncoder(channel)) {
            halt("Failed to initialise Position mode.");
        }
    }
    Serial.println("Unit 4EncoderMotor Driver ready");
}

void loop()
{
    moveTo(TARGET_POSITION, TIMEOUT_MS);
    delay(1000);
    moveTo(0, TIMEOUT_MS);
    delay(1000);
}

まず 4 チャンネルそれぞれで clearEncoder(channel) を呼び出してカウントをゼロにします。続いて runPosition(1320, 100, POSITION_PID, channel) で 4 台とも 1320 カウント(出力軸 1 回転)まで移動させます。100 は位置ループの出力制限で、POSITION_PID = {1, 1, 17} はファームウェアのデフォルトパラメーターです。4 チャンネルすべてが目標に到達すると position reached を出力します。

シリアル出力例:

Unit 4EncoderMotor Driver ready
target=1320 M1[encoder=1318] M2[encoder=1319] M3[encoder=1316] M4[encoder=1317]
position reached

3.4 ソフトスタートとソフトストップ(4 チャンネル同期)

cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
#include <M5Unified.h>
#include <M5Unit-EncoderMotor-Driver.h>

// Product selector sets the default address and channel count:
// U232 = 0x2F (1 channel), U233 = 0x24 (4 channels)
M5UnitEncoderMotor motors(M5Unit_4EncoderMotor_Driver);

// Draw into an offscreen canvas so a full screen refresh does not flicker
M5Canvas canvas(&M5.Display);

constexpr int8_t I2C_SDA_PIN     = 2;  // CoreS3 PORT.A
constexpr int8_t I2C_SCL_PIN     = 1;
constexpr uint32_t I2C_FREQUENCY = 400000;
constexpr int8_t STEP_DUTY       = 127;   // Duty step, the ramp replaces the jump
constexpr uint32_t RUN_MS        = 4000;  // Duration of each segment
constexpr uint32_t STEP_MS       = 50;    // Ramp sampling interval

void halt(const char *message)
{
    Serial.println(message);
    while (true) {
        delay(1000);
    }
}

// Center the status screen and mix three font sizes so the key value stands out.
void showScreen(const char *title, const char *value, const char *detail1, const char *detail2)
{
    canvas.fillScreen(TFT_BLACK);
    canvas.setTextDatum(middle_center);

    canvas.setFont(&fonts::DejaVu18);
    canvas.setTextColor(TFT_LIGHTGREY);
    canvas.drawString(title, canvas.width() / 2, 32);

    canvas.setFont(&fonts::DejaVu40);
    canvas.setTextColor(TFT_WHITE);
    canvas.drawString(value, canvas.width() / 2, 112);

    canvas.setFont(&fonts::DejaVu12);
    canvas.setTextColor(TFT_LIGHTGREY);
    if (detail1 && detail1[0]) {
        canvas.drawString(detail1, canvas.width() / 2, 176);
    }
    if (detail2 && detail2[0]) {
        canvas.drawString(detail2, canvas.width() / 2, 204);
    }

    canvas.pushSprite(0, 0);
}

void drawStatus(const char *state, int8_t duty)
{
    int8_t speed[4] = {0, 0, 0, 0};
    for (uint8_t channel = 0; channel < motors.motorCount() && channel < 4; ++channel) {
        motors.getSpeed(speed[channel], channel);
    }

    char value[16];
    char detail1[48];
    char detail2[48];
    snprintf(value, sizeof(value), "%+d", speed[0]);
    snprintf(detail1, sizeof(detail1), "%s   duty %+d", state, duty);
    snprintf(detail2, sizeof(detail2), "M2 %+d   M3 %+d   M4 %+d", speed[1], speed[2], speed[3]);
    showScreen("SOFT START", value, detail1, detail2);
}

// Stop first, so every ramp starts from standstill.
void brakeAndWait()
{
    for (uint8_t channel = 0; channel < motors.motorCount(); ++channel) {
        motors.setPWMDuty(0, channel);
    }
    for (int i = 0; i < 100; ++i) {
        bool stopped = true;
        for (uint8_t channel = 0; channel < motors.motorCount() && channel < 4; ++channel) {
            int8_t speed = 0;
            motors.getSpeed(speed, channel);
            if (abs(speed) > 1) {
                stopped = false;
            }
        }
        if (stopped) {
            return;
        }
        delay(50);
    }
}

// Step the duty on all channels and sample the speed to show the ramp.
void holdDuty(const char *state, int8_t duty, uint32_t duration_ms)
{
    for (uint8_t channel = 0; channel < motors.motorCount(); ++channel) {
        motors.setPWMDuty(duty, channel);
    }
    for (uint32_t elapsed = 0; elapsed < duration_ms; elapsed += STEP_MS) {
        drawStatus(state, duty);
        Serial.printf("%s t=%4lums duty=%+d", state, static_cast<long>(elapsed), duty);
        for (uint8_t channel = 0; channel < motors.motorCount(); ++channel) {
            int8_t speed = 0;
            motors.getSpeed(speed, channel);
            Serial.printf(" M%u[speed=%+d]", channel + 1, speed);
        }
        Serial.println();
        delay(STEP_MS);
    }
}

void setup()
{
    auto cfg = M5.config();
    cfg.output_power = true;
    M5.begin(cfg);
    canvas.createSprite(M5.Display.width(), M5.Display.height());
    Serial.begin(115200);

    while (!motors.begin(&Wire, 0, I2C_SDA_PIN, I2C_SCL_PIN, I2C_FREQUENCY)) {
        Serial.println("Unit 4EncoderMotor Driver not found");
        delay(1000);
    }
    delay(100);  // give the unit time to finish the previous write
    for (uint8_t channel = 0; channel < motors.motorCount(); ++channel) {
        if (!motors.setMotorMode(M5_UNIT_ENCODER_MOTOR_MODE_NORMAL, channel) || !motors.setPWMDuty(0, channel)) {
            halt("Failed to initialise Normal mode.");
        }
        // Soft start works in Normal and Speed mode here, but not in Position mode.
        // The bit is saved to flash, so set it once here instead of in loop().
        if (!motors.setSoftStartStop(true, channel)) {
            halt("Failed to enable soft start / stop.");
        }
    }
    Serial.println("Soft start / stop enabled");
    Serial.println("Unit 4EncoderMotor Driver ready");
}

void loop()
{
    brakeAndWait();
    holdDuty("run", STEP_DUTY, RUN_MS);
    holdDuty("stop", 0, RUN_MS);
}
 

4 チャンネルのソフトスタート/ソフトストップは、レジスタ 0xD1 の bit0~bit3 でそれぞれ個別に制御します。4 チャンネルユニットでは、これらのビットは Normal(オープンループ PWM)モードおよび Speed モードで有効ですが、Position モードでは無効です。

setSoftStartStop(true, channel) で有効にすると、デューティ比はステップ状に変化せず、ファームウェア内部のランプに従って徐々に上昇・下降します。この設定はユニットの Flash メモリに保存され、電源を切っても保持されます。そのため、setup() 内でチャンネルごとに一度だけ設定し、loop() 内では再度書き込まないでください。

このサンプルでは、まず brakeAndWait() で 4 台のモーターすべてが完全に停止するまで待機します。その後、デューティ比の指令値を 0 から 127 へステップ状に変更し、続いて 0 に戻します。回転速度を 50 ms ごとにサンプリングすることで、回転速度の立ち上がりと減速を確認できます。以下のシリアル出力例における M2~M4 の値は、全 4 チャンネルにモーターを接続した場合の参考値です。

シリアル出力例:

Soft start / stop enabled
Unit 4EncoderMotor Driver ready
run t=   0ms target=+20 M1[measured=+0] M2[measured=+0] M3[measured=+0] M4[measured=+0]
run t= 100ms target=+20 M1[measured=+12] M2[measured=+12] M3[measured=+11] M4[measured=+12]
run t= 200ms target=+20 M1[measured=+20] M2[measured=+20] M3[measured=+19] M4[measured=+20]
stop t=   0ms target=+0 M1[measured=+20] M2[measured=+20] M3[measured=+19] M4[measured=+20]
stop t= 100ms target=+0 M1[measured=+0] M2[measured=+0] M3[measured=+0] M4[measured=+0]

3.5 RGB インジケーター

cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
#include <M5Unified.h>
#include <M5Unit-EncoderMotor-Driver.h>

// Product selector sets the default address and channel count:
// U232 = 0x2F (1 channel), U233 = 0x24 (4 channels)
M5UnitEncoderMotor motors(M5Unit_4EncoderMotor_Driver);

// Draw into an offscreen canvas so a full screen refresh does not flicker
M5Canvas canvas(&M5.Display);

constexpr int8_t I2C_SDA_PIN     = 2;  // CoreS3 PORT.A
constexpr int8_t I2C_SCL_PIN     = 1;
constexpr uint32_t I2C_FREQUENCY = 400000;

struct ColorStep {
    const char *name;
    uint8_t red;
    uint8_t green;
    uint8_t blue;
};

constexpr ColorStep STEPS[] = {
    {"red", 255, 0, 0},    {"green", 0, 255, 0},    {"blue", 0, 0, 255},
    {"yellow", 255, 255, 0}, {"cyan", 0, 255, 255}, {"magenta", 255, 0, 255},
    {"off", 0, 0, 0},
};
constexpr uint8_t BRIGHTNESS = 80;  // 0 ~ 255
constexpr uint32_t STEP_MS   = 800;

void halt(const char *message)
{
    Serial.println(message);
    while (true) {
        delay(1000);
    }
}

// Center the status screen and mix three font sizes so the key value stands out.
void showScreen(const char *title, const char *value, const char *detail1, const char *detail2)
{
    canvas.fillScreen(TFT_BLACK);
    canvas.setTextDatum(middle_center);

    canvas.setFont(&fonts::DejaVu18);
    canvas.setTextColor(TFT_LIGHTGREY);
    canvas.drawString(title, canvas.width() / 2, 32);

    canvas.setFont(&fonts::DejaVu40);
    canvas.setTextColor(TFT_WHITE);
    canvas.drawString(value, canvas.width() / 2, 112);

    canvas.setFont(&fonts::DejaVu12);
    canvas.setTextColor(TFT_LIGHTGREY);
    if (detail1 && detail1[0]) {
        canvas.drawString(detail1, canvas.width() / 2, 176);
    }
    if (detail2 && detail2[0]) {
        canvas.drawString(detail2, canvas.width() / 2, 204);
    }

    canvas.pushSprite(0, 0);
}

void setup()
{
    auto cfg = M5.config();
    cfg.output_power = true;
    M5.begin(cfg);
    canvas.createSprite(M5.Display.width(), M5.Display.height());
    Serial.begin(115200);

    while (!motors.begin(&Wire, 0, I2C_SDA_PIN, I2C_SCL_PIN, I2C_FREQUENCY)) {
        Serial.println("Unit 4EncoderMotor Driver not found");
        delay(1000);
    }
    if (!motors.setRGBBrightness(BRIGHTNESS)) {
        halt("Failed to set RGB brightness.");
    }
    Serial.println("RGB demo ready");
}

void loop()
{
    for (const auto &step : STEPS) {
        const bool ok = motors.setRGBColor(step.red, step.green, step.blue);
        delay(100);

        uint8_t red = 0;
        uint8_t green = 0;
        uint8_t blue = 0;
        uint8_t brightness = 0;
        const bool read_ok = motors.getRGBColor(red, green, blue) && motors.getRGBBrightness(brightness);

        char value[16];
        char detail1[48];
        char detail2[48];
        snprintf(value, sizeof(value), "%s", step.name);
        snprintf(detail1, sizeof(detail1), "R%3u G%3u B%3u", red, green, blue);
        snprintf(detail2, sizeof(detail2), "brightness %u", brightness);
        showScreen("RGB", value, detail1, detail2);

        Serial.printf("set=%s rgb=(%u,%u,%u) brightness=%u result=%s read=(%u,%u,%u)/%u read_result=%s\n",
                      step.name, step.red, step.green, step.blue, BRIGHTNESS, ok ? "OK" : "FAIL", red, green,
                      blue, brightness, read_ok ? "OK" : "FAIL");
        delay(STEP_MS);
    }
}

4 チャンネルユニットは 1 個の RGB インジケーターを共有します。setRGBBrightness(80) で明るさを設定した後、7 種類の色を順に送信します。各ステップで getRGBColor() と getRGBBrightness() を使用して色と明るさを読み戻し、シリアル出力に設定値と読み戻し値を出力します。

シリアル出力例:

RGB demo ready
set=red rgb=(255,0,0) brightness=80 result=OK read=(255,0,0)/80 read_result=OK
set=green rgb=(0,255,0) brightness=80 result=OK read=(0,255,0)/80 read_result=OK
set=blue rgb=(0,0,255) brightness=80 result=OK read=(0,0,255)/80 read_result=OK
set=yellow rgb=(255,255,0) brightness=80 result=OK read=(255,255,0)/80 read_result=OK
set=cyan rgb=(0,255,255) brightness=80 result=OK read=(0,255,255)/80 read_result=OK
set=magenta rgb=(255,0,255) brightness=80 result=OK read=(255,0,255)/80 read_result=OK
set=off rgb=(0,0,0) brightness=80 result=OK read=(0,0,0)/80 read_result=OK

4. コンパイルと書き込み

上記のサンプルプログラムのいずれかをスケッチの編集領域にコピーし、デバイスのポートを選択します(詳細はプログラムのコンパイルと書き込みを参照)。Arduino IDE 左上の書き込みボタンをクリックし、処理が完了するまで待ちます。

Page Tools
PDF
On This Page