メインコンテンツまでスキップ

ハードウェア実験

概要​

3 つの実験を、やさしいものから順に行います — IMU から角度を読み取り、Bluetooth LE で 1 つのモーターを動かし、最後にオンボードボタンで RGB ストリップを切り替えます。どれも 1 つのスケッチだけで完結します:準備して、書き込んで、観察するだけです。

実験 1 と 3 はキットだけで実行できます。実験 2 には、さらにモーターケーブルとスマートフォン用の BLE スキャナアプリが必要です。

はじめに​

ハードウェアの準備​

必要なのは XIAO Robot Kit、USB-C データケーブル、そしてコンピュータです — これで実験 1 と 2 をカバーできます。実験 3 ではさらに 1 つ部品を追加します:D13 に配線した WS2812 ライトボードです(写真では CH Maker Ed のものを使用していますが、どのボードでも構いません。LED_COUNT はそのボード上の LED 個数に合わせてください)。

ヒント

モーターやサーボは大きな電流を消費します。コンピュータの USB ポートだけでは電力が足りない場合があるため、それらを駆動するときは バッテリーコネクタ からキットに給電してください。

ソフトウェアの準備​

ESP32 ボードパッケージをインストールした Arduino IDE を用意し、ツール > ボード で XIAO_ESP32S3_PLUS を選択します — まだインストールしていない場合は、Getting Started に手順があります。ESP32 コア以外に追加でインストールするものはありません:3 つのスケッチはすべて、ボードパッケージに最初から含まれているものだけでビルドできます。

実験 1: IMU ゼロキャリブレーション + オイラー角融合​

このスケッチは、IMU の生の加速度と回転速度を 3 つの角度 — ロール、ピッチ、ヨー — に変換し、度数で 1 秒間に 50 回出力します。センサーライブラリは一切使っていません:Wire でレジスタを読み出し、姿勢フィルタはファイル内にそのまま書かれているので、たとえ一切変更しないとしても読む価値があります。

処理を行うのは 2 つの部分です。readImu() は ±2 g と ±2000 dps レンジの感度で生のカウント値をスケーリングし、g と dps に変換します。続いて mahony_update() が Mahony 補完フィルタを実行します:高速な応答のためにジャイロを積分し、その結果を KP で測定された重力ベクトルへ引き戻し、姿勢をクォータニオンとして保持することで、どの軸もジンバルロックに陥らないようにします。quat_to_euler() はそれを出力ごとに 3 つの角度へ変換し、fmtAng() が各角度を固定幅にパディングして、数値が変わっても列がずれないようにします。

ステップ 1. スケッチを作成する

Arduino IDE で File > New Sketch を開き、テンプレートコードを削除して、以下のスケッチを貼り付けます:

完全なコード
/* SPDX-License-Identifier: MIT */
/* Experiment 1: LSM6DS3TR-C + Mahony AHRS -> roll/pitch/yaw (deg), zero-lib.
* Warm-up 12s -> auto-cal 6s (hold still). Still-tracker nulls yaw drift.
* Press KEY (D11) to re-zero. I2C SDA=D4 SCL=D5, addr 0x6A, Serial 115200.
*
* The whole chain is four calls: readImu() -> mahony_update() ->
* quat_to_euler() -> Serial. Everything between them is written out here. */

#include <Arduino.h>
#include <Wire.h>
#include <math.h>
#include <stdlib.h>

/* The seven registers this sketch touches; names follow the LSM6DS3TR-C
* datasheet, so you can look any of them up. */
#define ADDR 0x6A /* I2C address, fixed by the chip */
#define WHO_AM_I 0x0F /* identity register, always reads 0x6A */
#define CTRL1_XL 0x10 /* accelerometer: output rate + full scale */
#define CTRL2_G 0x11 /* gyroscope: output rate + full scale */
#define CTRL3_C 0x12 /* block data update + register auto-increment */
#define OUT_TEMP_L 0x20 /* temperature, first byte of the output block */
#define OUTX_L_G 0x22 /* gyro X/Y/Z, 6 bytes */
#define OUTX_L_XL 0x28 /* accel X/Y/Z, 6 bytes */

#define PIN_SDA 5 // D4
#define PIN_SCL 6 // D5
#define PIN_BUTTON 38 // KEY (D11), active low

#define ACCEL_LSB 0.000061f // +-2g, g/LSB
#define GYRO_LSB 0.070f // +-2000dps, dps/LSB

#define ODR_HZ 104 // output data rate set in setup()
#define PERIOD_US (1000000u / ODR_HZ) // one sample every 9.6 ms
#define CALIB_MS 6000 // length of the zero-offset average
#define SETTLE_MS 12000 // warm-up before that average starts

/* Filter gains: KP pulls the attitude toward the measured gravity vector,
* KI would trim a residual rate and is left at zero here. */
#define KP 2.0f
#define KI 0.0f
#define STILL_DPS 1.0f // sum|gyro| under this = still
#define STILL_MS 1500 // still time before auto-null
#define BIAS_ALPHA 0.01f // bias leak per tick

#define RAD2DEG 57.2958f
#define PI 3.14159265f

/* Attitude is carried as a quaternion: four numbers, no gimbal lock.
* ImuSample / ImuBias hold the scaled sensor values in g and dps. */
struct Quat { float w, x, y, z; };
struct Mahony { Quat q; float kp, ki, dt; float integral[3]; };
struct ImuSample { float gx, gy, gz, ax, ay, az; };
struct ImuBias { float gx, gy, gz, ax, ay, az; };

static Mahony mahony;
static ImuBias bias; /* offset subtracted from every reading */
static ImuSample cur; /* last sample, in g and dps */
static float imuTemp;
static unsigned long gLastUs; /* timestamp of the previous filter update */

/* Write one 8-bit register. */
static void wr(uint8_t r, uint8_t v) {
Wire.beginTransmission(ADDR); Wire.write(r); Wire.write(v); Wire.endTransmission(true);
}
/* Read n bytes from register r; false = the bus did not answer. */
static bool rd(uint8_t r, uint8_t *b, uint8_t n) {
Wire.beginTransmission(ADDR); Wire.write(r);
if (Wire.endTransmission(false)) return false;
if (Wire.requestFrom((int)ADDR, (int)n) != n) return false;
for (uint8_t i = 0; i < n; i++) b[i] = Wire.read();
return true;
}
/* Two little-endian bytes -> one signed 16-bit sample. */
static int16_t i16(const uint8_t *p) { return (int16_t)(p[0] | p[1] << 8); }

/* Grab one full sample: gyro, accel, temperature. Counts are multiplied by the
* sensitivity of the +-2 g / +-2000 dps ranges, so cur is already in g and dps. */
static bool readImu() {
uint8_t b[6];
if (!rd(OUTX_L_G, b, 6)) return false;
cur.gx = i16(&b[0]) * GYRO_LSB;
cur.gy = i16(&b[2]) * GYRO_LSB;
cur.gz = i16(&b[4]) * GYRO_LSB;
if (!rd(OUTX_L_XL, b, 6)) return false;
cur.ax = i16(&b[0]) * ACCEL_LSB;
cur.ay = i16(&b[2]) * ACCEL_LSB;
cur.az = i16(&b[4]) * ACCEL_LSB;
uint8_t t[2];
if (rd(OUT_TEMP_L, t, 2)) imuTemp = 25.0f + (float)i16(t) / 256.0f;
return true;
}

/* w = 1, x = y = z = 0: the quaternion that means "no rotation". */
static void quat_identity() { mahony.q.w = 1.0f; mahony.q.x = mahony.q.y = mahony.q.z = 0.0f; }

/* A quaternion has to stay unit length, or the rotation it describes stretches.
* Renormalize after every integration step; a zero-length q means broken state. */
static void quat_normalize() {
float n = sqrtf(mahony.q.w * mahony.q.w + mahony.q.x * mahony.q.x
+ mahony.q.y * mahony.q.y + mahony.q.z * mahony.q.z);
if (n < 1e-6f) { quat_identity(); return; }
mahony.q.w /= n; mahony.q.x /= n; mahony.q.y /= n; mahony.q.z /= n;
}

// quaternion -> ZYX euler (rad)
/* roll about X, pitch about Y, yaw about Z, in that order. asinf() is clamped
* because rounding can push its argument just past +-1. */
static void quat_to_euler(float *roll, float *pitch, float *yaw) {
float w = mahony.q.w, x = mahony.q.x, qy = mahony.q.y, z = mahony.q.z;
*roll = atan2f(2.0f * (w * x + qy * z), 1.0f - 2.0f * (x * x + qy * qy));
float sp = 2.0f * (w * qy - z * x);
*pitch = (sp >= 1.0f) ? PI * 0.5f : (sp <= -1.0f) ? -PI * 0.5f : asinf(sp);
*yaw = atan2f(2.0f * (w * z + x * qy), 1.0f - 2.0f * (qy * qy + z * z));
}

/* Reset the filter to "level, not turning" and seed it with the gains.
* dt starts at the nominal 1/ODR; loop() replaces it with the measured one. */
static void mahony_init() {
quat_identity();
mahony.kp = KP; mahony.ki = KI; mahony.dt = 1.0f / ODR_HZ;
mahony.integral[0] = mahony.integral[1] = mahony.integral[2] = 0.0f;
}

/* One complementary-filter step: the gyro says how fast the board is turning,
* the accelerometer says where "down" is. Blend them, integrate, renormalize. */
static void mahony_update(float ax, float ay, float az, float gx, float gy, float gz) {
const float dt = mahony.dt;
const float twoKp = 2.0f * mahony.kp, twoKi = 2.0f * mahony.ki;

/* Normalize the measured gravity vector; a zero vector carries no direction,
* which happens during a hard shake, so skip that step. */
float n = sqrtf(ax * ax + ay * ay + az * az);
if (n < 1e-6f) return;
ax /= n; ay /= n; az /= n;

float q0 = mahony.q.w, q1 = mahony.q.x, q2 = mahony.q.y, q3 = mahony.q.z;

// estimated gravity dir, error = cross(measured, estimated)
/* v = where gravity should point for the current attitude; the cross product
* with the measured vector is the correction the filter has to apply. */
float vx = 2.0f * (q1 * q3 - q0 * q2);
float vy = 2.0f * (q0 * q1 + q2 * q3);
float vz = q0 * q0 - q1 * q1 - q2 * q2 + q3 * q3;
float ex = ay * vz - az * vy;
float ey = az * vx - ax * vz;
float ez = ax * vy - ay * vx;

/* KI is zero here, so this stays at zero; kept so raising KI works. */
mahony.integral[0] += twoKi * ex * dt;
mahony.integral[1] += twoKi * ey * dt;
mahony.integral[2] += twoKi * ez * dt;

/* Corrected rate in rad/s: gyro reading + KP * attitude error. */
const float d2r = PI / 180.0f; // dps -> rad/s
gx = gx * d2r + twoKp * ex + mahony.integral[0];
gy = gy * d2r + twoKp * ey + mahony.integral[1];
gz = gz * d2r + twoKp * ez + mahony.integral[2];

// first-order quaternion integration
/* q_dot = 0.5 * q ⊗ w, stepped by dt. Simple, and accurate enough at 104 Hz. */
float hdt = 0.5f * dt;
mahony.q.w += hdt * (-q1 * gx - q2 * gy - q3 * gz);
mahony.q.x += hdt * ( q0 * gx + q2 * gz - q3 * gy);
mahony.q.y += hdt * ( q0 * gy - q1 * gz + q3 * gx);
mahony.q.z += hdt * ( q0 * gz + q1 * gy - q2 * gx);

quat_normalize();
}

/* Average the sensor for CALIB_MS while the board sits still, and store that
* average as the offset. Held still, a gyro should read zero and the accel
* should read exactly 1 g on one axis: whatever is left over is the error. */
static void calibrateImu() {
float gxs = 0, gys = 0, gzs = 0, axs = 0, ays = 0, azs = 0;
int n = 0;
unsigned long t0 = millis(), tick = micros();
while (millis() - t0 < CALIB_MS) {
if ((unsigned long)(micros() - tick) >= PERIOD_US) {
tick = micros();
if (readImu()) {
gxs += cur.gx; gys += cur.gy; gzs += cur.gz;
axs += cur.ax; ays += cur.ay; azs += cur.az;
n++;
}
}
}
if (n == 0) return; /* no sample landed - keep the old offsets */
float inv = 1.0f / n;
float gxm = gxs * inv, gym = gys * inv, gzm = gzs * inv;
float axm = axs * inv, aym = ays * inv, azm = azs * inv;

// remove 1g from the dominant accel axis
/* Whichever axis carries the largest reading is the one pointing down;
* subtract 1 g from it so a level board reads 0 / 0 / 0 afterwards. */
float aa[3] = { fabsf(axm), fabsf(aym), fabsf(azm) };
int axis = 0;
if (aa[1] > aa[0]) axis = 1;
if (aa[2] > aa[axis]) axis = 2;
float av[3] = { axm, aym, azm };
float sign = (av[axis] > 0.0f) ? 1.0f : -1.0f;

bias.gx = gxm; bias.gy = gym; bias.gz = gzm;
bias.ax = axm; bias.ay = aym; bias.az = azm;
if (axis == 0) bias.ax -= sign * 1.0f;
else if (axis == 1) bias.ay -= sign * 1.0f;
else bias.az -= sign * 1.0f;
}

/* The KEY handler: say so, measure again, and restart the filter from level. */
static void recalibrate() {
Serial.println("re-cal (keep still...)");
calibrateImu();
mahony_init();
gLastUs = micros();
}

// right-aligned, fixed-width "+12.3" style
/* dtostrf() pads on the left, which would put the spaces between the sign and
* the digits. Move the sign in front of them so the columns line up. */
static void fmtAng(char *out, float deg, int width) {
char m[12];
dtostrf(deg < 0.0f ? -deg : deg, width - 1, 1, m);
int i = 0;
while (i < width - 1 && m[i] == ' ') i++; // skip dtostrf pad
int o = 0;
while (o < i) out[o++] = ' ';
out[o++] = (deg < 0.0f) ? '-' : '+';
for (int k = i; k < width - 1; k++) out[o++] = m[k];
out[o] = '\0';
}

void setup() {
Serial.begin(115200);
delay(200);
Wire.begin(PIN_SDA, PIN_SCL); /* I2C on D4 / D5 */
Wire.setClock(400000); /* 400 kHz fast mode */
pinMode(PIN_BUTTON, INPUT_PULLUP);

uint8_t id = 0;
/* Talk to the chip before trusting anything it sends. */
if (!rd(WHO_AM_I, &id, 1) || id != 0x6A) {
Serial.println("IMU init failed");
while (1) delay(1000);
}
/* Output rate and full scale, matching ACCEL_LSB / GYRO_LSB above. */
wr(CTRL1_XL, 0x40); // +-2g @104Hz
wr(CTRL2_G, 0x4C); // +-2000dps @104Hz
wr(CTRL3_C, 0x44); // BDU + IF_INC
mahony_init();

/* Warm-up: the temperature sensor needs a moment, and the user needs a
* visible countdown before being asked to hold the board still. */
Serial.println("warm-up...");
for (unsigned long s = millis(); millis() - s < SETTLE_MS; ) {
readImu(); delay(500);
Serial.print("temp="); Serial.println(imuTemp, 1);
}
Serial.println("keep still...");
calibrateImu();
gLastUs = micros();
Serial.println("roll=deg pitch=deg yaw=deg temp=C");
}

void loop() {
static unsigned long tPrint = 0;
static uint32_t stillSince = 0;

// button: debounce + falling edge -> re-zero
/* Same debounce as Example 1 in Getting Started: a level counts only after
* it has held for 10 ms, and only the press edge starts a re-calibration. */
static bool lastRaw = HIGH, lastStable = HIGH;
static uint32_t lastChange = 0;
uint32_t bNow = millis();
bool bCur = (digitalRead(PIN_BUTTON) == LOW);
if (bCur != lastRaw) { lastRaw = bCur; lastChange = bNow; }
if ((uint32_t)(bNow - lastChange) >= 10 && bCur != lastStable) {
lastStable = bCur;
if (lastStable) recalibrate();
}

// non-blocking tick, measured dt
/* Run the filter only when a new sensor sample is due. dt is measured, not
* assumed, so a slow print or a busy Wi-Fi stack cannot shift the angles. */
unsigned long nowUs = micros();
if (nowUs - gLastUs >= PERIOD_US) {
mahony.dt = (float)(nowUs - gLastUs) / 1000000.0f;
gLastUs = nowUs;
if (readImu()) {
float gx = cur.gx - bias.gx;
float gy = cur.gy - bias.gy;
float gz = cur.gz - bias.gz;

// still-tracker: null residual zero-rate so yaw holds flat
/* A gyro never reads exactly zero, and any leftover rate is
* integrated into yaw forever. While the board is still, leak a
* little of that leftover into the stored offset instead. */
if (fabsf(gx) + fabsf(gy) + fabsf(gz) < STILL_DPS) {
if (stillSince == 0) stillSince = millis();
if (millis() - stillSince >= STILL_MS) {
bias.gx += BIAS_ALPHA * gx;
bias.gy += BIAS_ALPHA * gy;
bias.gz += BIAS_ALPHA * gz;
}
} else {
stillSince = 0;
}

mahony_update(cur.ax - bias.ax, cur.ay - bias.ay, cur.az - bias.az,
gx, gy, gz);
}
}

/* Print 50 times a second: the angles are filtered, so a faster line on the
* Serial Monitor would only repeat the same numbers. */
uint32_t now = millis();
if (now - tPrint >= 20) {
tPrint = now;
float roll, pitch, yaw;
quat_to_euler(&roll, &pitch, &yaw);
char rb[12], pb[12], yb[12];
fmtAng(rb, roll * RAD2DEG, 6);
fmtAng(pb, pitch * RAD2DEG, 6);
fmtAng(yb, yaw * RAD2DEG, 7);
Serial.print("roll="); Serial.print(rb);
Serial.print(" pitch="); Serial.print(pb);
Serial.print(" yaw="); Serial.print(yb);
Serial.print(" temp="); Serial.print(imuTemp, 1);
Serial.println("C");
}
delay(0); // yield to RTOS (loop is non-blocking but time-stamped)
}

ステップ 2. スケッチを書き込む

Tools > Board が XIAO_ESP32S3_PLUS であること、そして Tools > Port にあなたのボードが表示されていることを確認し、Upload(→)をクリックします。

ステップ 3. 結果を確認する

右上の虫眼鏡アイコンから Serial Monitor を開き、ボーレートを 115200 に設定します。最初の 12 秒間はダイ温度が 1 秒に 2 回出力され、その次の 6 秒間でジャイロのオフセットを測定します。その後、角度がスクロールし始めます:

warm-up...
temp=27.4
keep still...
roll=deg pitch=deg yaw=deg temp=C
roll= +0.3 pitch= -1.2 yaw= +0.0 temp=27.9C
roll= +0.4 pitch= -1.1 yaw= +0.1 temp=27.9C

ボードを前後に傾け、次に左右にロールさせて、どの角度が反応するかを確認します:

同じ傾きが、数値として Serial Monitor にどのように表示されるかを見てみましょう:

ボードを平らな場所に置き、オンボードの KEY ボタンを押します。するとスケッチは re-cal (keep still...) と表示し、再度オフセットを測定して、角度はほぼゼロ付近に戻ります。

ヒント

yaw は絶対値ではなく相対値です。このボードには磁力計がないため、スケッチは最後にフィルタをリセットしてからどれだけ回転したかしか分かりません — どちらの方向が北かは分からないのです。KEY を押してゼロ点を取り直し、長時間の使用ではゆっくりとドリフトすることを想定してください。

ゼロ点取り直しとチューニング​

ジャイロが完全にゼロを示すことはなく、残ったオフセットが積分されて、yaw がゆっくりとドリフトしていきます。スケッチはボードが静止している間にそのオフセットを測定します(これが 18 秒のウォームアップです)。そして KEY を押すと、必要なときに再測定します — 再書き込みは不要です。

スケッチ冒頭の 4 つの #define によって、デフォルト値が合わない場合の調整ができます。上のログはデフォルト値で取得したものです。

定数デフォルトこんなときに調整
KP2.0傾きに追従するまで時間がかかりすぎる(値を上げる)、または角度がピクピクする(値を下げる)場合。
STILL_DPS1.0ボードを平らに置いても yaw がドリフトする(値を下げる)、またはゆっくりと意図的に回転させたのに静止と誤判定される(値を上げる)場合。
BIAS_ALPHA0.01ドリフトがすぐに戻ってきてしまう(値を上げる) — ただしその場合、本物のゆっくりした回転もゼロに引き寄せられてしまいます。
CALIB_MS6000ゼロ点取り直しの再現性が十分でない(値を上げる)場合。ただしその分、KEY を押してから待つ時間が長くなります。

実験 2: エンコーダモーターの BLE 制御​

このスケッチはボードを BLE ペリフェラルとして動作させ、エンコーダのエッジをカウントして M1 モーターを動かします。これにより、一定時間ではなく、コマンドごとに正確な回転数だけ回すことができます。set 1 と書き込むと 10 回転して停止し、set 1 20 と書き込むと 20 回転します。

位置ループがこのスケッチの要となる部分です。execCmd() は、その時点のエンコーダカウントから目標値を取り(gTarget = gStart + dir × revs × 4848)、loop() はカウントがそこに到達したらモーターを停止させます。そのためオーバーシュートが次の動作に持ち越されることはありません。エンコーダのエッジは 16 エントリのクアドラチャテーブルを使って割り込み内でデコードされます。BLE の書き込みは Bluetooth タスクで受信されるため、4 スロットのキューに積まれ、loop() によって実行されます — モーターは常に 1 つのスレッドからのみ駆動されます。MOTOR_INVERT は駆動の極性を補正し、+duty が常にカウントを増加させるようにします。また、カウントが逆方向に進んだ場合には動作を中止するガードも入っています。

ハードウェア側はケーブル 1 本だけで済みます — ジャンパー線もブレッドボードも不要です:

ステップ 1. スケッチを作成する

Arduino IDE で File > New Sketch を開き、テンプレートコードを削除して、以下のスケッチを貼り付けます:

Full code
/* SPDX-License-Identifier: MIT */
/* Experiment 2: BLE Encoder Motor, BLE | Serial -> M1 encoder motor, exact position move.
* set 1 forward 10 rev set 0 stop (coast) set 1 20 forward 20 rev
* set -1 reverse 10 rev revs = 1..255, default REVS_PER_CMD
* target = count_now + dir * revs * 4848 counts, so overshoot never accumulates.
* The move is measured when the command is executed (BLE writes are queued, so
* that is at most one loop period after arrival). Encoder: 4848 counts/rev (x4
* quadrature). Commands are case-insensitive.
* BLE: "XIAO Robot Kit", service d3f1e2a4-0000-..., char d3f1e2a4-0001-... (WRITE|WRITE_NR). */

#include <Arduino.h>
#include <string.h>
#include <stdio.h>
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEAdvertising.h>

#define PIN_M1_IN1 2 /* D1 */
#define PIN_M1_IN2 3 /* D2 */
#define PIN_ENC_A 4 /* D3 */
#define PIN_ENC_B 41 /* D14 */

#define MOTOR_PWM_FREQ 20000
#define MOTOR_PWM_RES 10
#define DEAD_ZONE 15 /* |duty| below this coasts */
#define RUN_DUTY 70 /* duty % while moving */
/* Drive polarity calibration: +duty MUST increase the encoder count, otherwise the
* position loop can never converge. Measured on this board: +duty decreased the
* count, hence MOTOR_INVERT = 1. If `set 1` spins the wrong way physically, swap
* the two M1 wires AND set this to 0 (both changes together keep the loop valid). */
#define MOTOR_INVERT 1

#define REVS_PER_CMD 10 /* default travel of `set ±1`; `set 1 <n>` overrides */
#define COUNTS_PER_REV 4848 /* 12 PPR x 4 quadrature x 101 gear */
#define GUARD_REVS 2 /* max wrong-way travel before abort (capped by revs) */
#define CMD_MAX_LEN 32 /* longest accepted command line, Serial and BLE */

#define SERVICE_UUID "d3f1e2a4-0000-4b6e-9c1d-5a7b8c9d0e1f"
#define CHARACTERISTIC_UUID "d3f1e2a4-0001-4b6e-9c1d-5a7b8c9d0e1f"
#define BLE_DEVICE_NAME "XIAO Robot Kit"

/* command = run state; "stop" is simply the command to go back to idle */
enum : uint8_t { CMD_NONE = 0, CMD_FWD, CMD_REV };
/* Names printed in the telemetry line, indexed by the run state. */
static const char *const kStateName[] = { "IDLE", "FWD", "REV" };

/* The move is a target count, not a duration: execCmd() sets gTarget from the
* count at that instant, and loop() stops the motor when the count gets there. */
static uint8_t gState = CMD_NONE; /* loop only */
static int32_t gTarget = 0; /* absolute encoder count to reach */
static int32_t gStart = 0; /* count when the current move began */
static int32_t gGuard = 0; /* wrong-way abort distance, in counts */

/* 4-slot queue of packed commands ((revs<<8)|cmd): BLE task writes, loop reads */
#define CMD_QUEUE_LEN 4
static volatile uint16_t gQueue[CMD_QUEUE_LEN];
static volatile uint8_t gQHead = 0, gQTail = 0;

/* quadrature x4 transition table: (prev<<2)|next -> step */
static const int8_t kQuad[16] = { 0, 1, -1, 0, -1, 0, 0, 1, 1, 0, 0, -1, 0, -1, 1, 0 };
static volatile int32_t encCount = 0;
static volatile uint8_t encState = 0;

static void IRAM_ATTR onEncoderChange() {
uint8_t n = (uint8_t)((digitalRead(PIN_ENC_A) << 1) | digitalRead(PIN_ENC_B));
encCount += kQuad[(encState << 2) | n];
encState = n;
}

static int32_t readEnc() { noInterrupts(); int32_t c = encCount; interrupts(); return c; }

/* Called from the BLE task. Producers only append; loop() is the consumer, so
* the motor is driven from one thread. A full queue drops the command. */
static void pushCmd(uint16_t packed) {
uint8_t h = gQHead;
if ((uint8_t)(h - gQTail) >= CMD_QUEUE_LEN) return; /* full: drop */
gQueue[h % CMD_QUEUE_LEN] = packed;
gQHead = (uint8_t)(h + 1);
}

/* duty -100..100, 0 = coast, +duty = count increasing */
static void motorSet(int duty) {
if (MOTOR_INVERT) duty = -duty;
if (duty > 100) duty = 100;
if (duty < -100) duty = -100;
if (duty > -DEAD_ZONE && duty < DEAD_ZONE) duty = 0;
uint32_t d = (uint32_t)((duty < 0 ? -duty : duty) * ((1u << MOTOR_PWM_RES) - 1) / 100);
ledcWrite(PIN_M1_IN1, duty > 0 ? d : 0);
ledcWrite(PIN_M1_IN2, duty < 0 ? d : 0);
}

/* all motor action happens here, in the loop task. packed = (revs<<8)|cmd,
* with revs already guaranteed to be 1..255 by parseCmd() */
static void execCmd(uint16_t packed) {
uint8_t cmd = (uint8_t)(packed & 0xFF);
int32_t revs = (int32_t)(packed >> 8);
if (cmd == CMD_NONE) {
gState = CMD_NONE;
motorSet(0);
Serial.println("stop (coast)");
return;
}
gState = cmd;
int8_t dir = (cmd == CMD_FWD) ? +1 : -1;
gStart = readEnc();
/* Reference from the current count, so a past overshoot never adds up. */
gTarget = gStart + dir * revs * COUNTS_PER_REV;
gGuard = (revs < GUARD_REVS ? revs : GUARD_REVS) * COUNTS_PER_REV;
motorSet(dir * RUN_DUTY);
Serial.printf("go %s %ld rev (from %ld target %ld)\n", dir > 0 ? "fwd" : "rev",
(long)revs, (long)gStart, (long)gTarget);
}

/* parse "set N [revs]" -> packed (revs<<8)|CMD_*, 0 if invalid (case tolerant) */
static uint16_t parseCmd(const char *s) {
char buf[CMD_MAX_LEN];
strncpy(buf, s, sizeof(buf) - 1);
buf[sizeof(buf) - 1] = '\0';
for (char *p = buf; *p; p++) if (*p >= 'a' && *p <= 'z') *p -= 32;

int n = 0, revs = 0;
/* 3-digit width caps keep a long digit run from overflowing int */
if (sscanf(buf, "SET %3d %3d", &n, &revs) < 1) {
Serial.println("bad cmd (set 1 | set 0 | set -1 [revs])");
return 0;
}
uint8_t cmd = (n > 0) ? CMD_FWD : (n < 0) ? CMD_REV : CMD_NONE; /* 0 = stop */
if (revs < 1 || revs > 255) revs = REVS_PER_CMD; /* out of range -> default */
return (uint16_t)(((uint16_t)revs << 8) | cmd);
}

/* BLE write -> parse -> queue. Runs in the Bluetooth task, never in loop(). */
class CmdCallbacks : public BLECharacteristicCallbacks {
void onWrite(BLECharacteristic *p) override {
String v = p->getValue();
uint16_t c = v.length() ? parseCmd(v.c_str()) : (uint16_t)0;
if (c) pushCmd(c);
}
};

/* BLE stops advertising on connect and never resumes it: re-arm every time */
static volatile bool gConnected = false; /* written from the BLE task */
static volatile bool gAdvActive = false;

static void startAdvertising() {
BLEAdvertising *adv = BLEDevice::getAdvertising();
adv->setScanResponse(true);

BLEAdvertisementData advData; /* primary packet */
advData.setFlags(0x06); /* general discoverable */
advData.setCompleteServices(BLEUUID(SERVICE_UUID));
adv->setAdvertisementData(advData);

BLEAdvertisementData respData; /* scan response: full name */
respData.setName(BLE_DEVICE_NAME);
adv->setScanResponseData(respData);

BLEDevice::startAdvertising();
gAdvActive = true;
}

class ServerCallbacks : public BLEServerCallbacks {
void onConnect(BLEServer *) override {
gConnected = true;
gAdvActive = false; /* the stack stopped advertising */
Serial.println("[BLE] connected");
}
void onDisconnect(BLEServer *) override {
gConnected = false;
gAdvActive = false; /* loop() re-arms the advertising */
Serial.println("[BLE] disconnected -> will re-advertise");
}
};

static bool bleInit() {
if (!BLEDevice::init(BLE_DEVICE_NAME)) return false;
BLEServer *srv = BLEDevice::createServer();
srv->setCallbacks(new ServerCallbacks());
BLEService *svc = srv->createService(SERVICE_UUID);
BLECharacteristic *ch = svc->createCharacteristic(
CHARACTERISTIC_UUID, BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_WRITE_NR);
ch->setCallbacks(new CmdCallbacks());
svc->start();
startAdvertising();
return true;
}

void setup() {
Serial.begin(115200);
delay(200);
Serial.println("Experiment 2: BLE Encoder Motor (M1 D1/D2, enc D3/D14)");

pinMode(PIN_M1_IN1, OUTPUT); digitalWrite(PIN_M1_IN1, LOW);
pinMode(PIN_M1_IN2, OUTPUT); digitalWrite(PIN_M1_IN2, LOW);
pinMode(PIN_ENC_A, INPUT_PULLUP);
pinMode(PIN_ENC_B, INPUT_PULLUP);
encState = (uint8_t)((digitalRead(PIN_ENC_A) << 1) | digitalRead(PIN_ENC_B));
attachInterrupt(digitalPinToInterrupt(PIN_ENC_A), onEncoderChange, CHANGE);
attachInterrupt(digitalPinToInterrupt(PIN_ENC_B), onEncoderChange, CHANGE);

/* 20 kHz sits above the audible range, so the motor does not whine. */
ledcAttach(PIN_M1_IN1, MOTOR_PWM_FREQ, MOTOR_PWM_RES);
ledcAttach(PIN_M1_IN2, MOTOR_PWM_FREQ, MOTOR_PWM_RES);
motorSet(0);

if (!bleInit()) { Serial.println("BLE init failed"); while (1) delay(1000); }

Serial.printf("BLE up: name=%s\n service=%s\n char(WRITE)=%s\n",
BLE_DEVICE_NAME, SERVICE_UUID, CHARACTERISTIC_UUID);
Serial.println("phone: scan with nRF Connect / LightBlue (not system Bluetooth)");
Serial.println("cmds: set 1 | set 0 | set -1 (optional revs: set 1 20)");
}

void loop() {
static String line;
static uint32_t tPrint = 0, tBlue = 0;
static int32_t lastCount = 0;
uint32_t now = millis();

/* local Serial command (same task as the consumer, so run it directly) */
while (Serial.available()) {
char c = (char)Serial.read();
if (c == '\n' || c == '\r') {
line.trim();
if (line.length()) {
uint16_t cmd = parseCmd(line.c_str());
if (cmd) execCmd(cmd);
}
line = "";
} else if (line.length() < CMD_MAX_LEN - 1) {
line += c;
}
}

/* drain BLE commands */
while (gQTail != gQHead) {
uint16_t cmd = gQueue[gQTail % CMD_QUEUE_LEN];
gQTail = (uint8_t)(gQTail + 1);
execCmd(cmd);
}

/* reached target? also abort if it runs the wrong way (polarity/encoder fault) */
if (gState != CMD_NONE) {
int32_t c = readEnc();
int32_t dir = (gState == CMD_FWD) ? +1 : -1;
if (dir * (gTarget - c) <= 0) {
Serial.printf("done: %.2f rev, enc=%ld (%.2f rev past target)\n",
(double)(dir * (c - gStart)) / COUNTS_PER_REV, (long)c,
(double)(dir * (c - gTarget)) / COUNTS_PER_REV);
execCmd(CMD_NONE);
} else if (dir * (c - gStart) < -gGuard) {
Serial.println("ABORT: motor turns the wrong way (check MOTOR_INVERT / wiring)");
execCmd(CMD_NONE);
}
}

/* keep the device discoverable */
if (now - tBlue >= 1000 && !gConnected && !gAdvActive) {
tBlue = now;
startAdvertising();
Serial.println("[BLE] advertising restarted");
}

/* telemetry: one line every 200 ms, so a move can be watched converging */
if (now - tPrint >= 200) {
int32_t c = readEnc();
float dt = (now - tPrint) / 1000.0f;
float rpm = dt > 0.0f
? (float)(c - lastCount) * 60.0f / ((float)COUNTS_PER_REV * dt) : 0.0f;
lastCount = c;
tPrint = now;
Serial.printf("state=%s count=%ld rpm=%.1f remain=%ld (%.2f rev) target=%ld\n",
kStateName[gState], (long)c, rpm,
(long)(gTarget - c),
(double)(gTarget - c) / COUNTS_PER_REV, (long)gTarget);
}

delay(5);
}

ステップ 2. スケッチを書き込む

Tools > Board が XIAO_ESP32S3_PLUS になっていることと、Tools > Port にボードが表示されていることを確認し、Upload(→)をクリックします。

ステップ 3. Bluetooth LE 経由でコマンドを送信する

このスケッチは XIAO Robot Kit という名前でアドバタイズし、書き込みを待ちます。スマートフォンのシステム Bluetooth 設定からはキャラクタリスティックへの書き込みができないため、BLE スキャナアプリが必要です。以下の手順では nRF Connect を使用します:

注記

nRF Connect は Nordic Semiconductor が公開しているサードパーティアプリです。キットの一部ではなく、Seeed Studio はこれをメンテナンスしていません。また、上記 2 つのリンクは公式ストアの掲載ページを指しています。nRF Connect は Nordic Semiconductor の商標です。

次に、4 枚のスクリーンショットのとおりに操作します:XIAO Robot Kit をスキャンして接続し、Unknown Service を開き、書き込みフィールドにコマンドを入力します。データ形式は 16 進数ではなく UTF-8 のままにしておきます。

次のいずれかの行を書き込みます。Serial Monitor でも同じコマンドが使えるので、スマートフォンをまったく使わなくても構いません:

コマンドモーターの動作
set 110 回転だけ前進して停止します。
set -110 回転だけ後進して停止します。
set 1 2020 回転だけ前進します。2 番目の数値は回転数で、1〜255 の範囲です。
set 0ただちに停止し、モーターを惰性で回転させます。

コマンドは大文字小文字を区別せず、回転数を指定しないコマンドは既定の 10 回転になります。

ログを読む​

Serial Monitor を 115200 で開きます。スケッチは起動時に一度だけ BLE 名と UUID を出力し、その後はコマンドごとに 1 行と、200 ms ごとにテレメトリ行を 1 行出力します。以下はスマートフォンから開始したセッションの例です:

[BLE] connected
go fwd 10 rev (from 0 target 48480)
state=FWD count=14400 rpm=150.0 remain=34080 (7.03 rev) target=48480
done: 10.00 rev, enc=48480 (0.00 rev past target)

実験 3: ボタン切り替え式 RGB LED​

ここでも LED ライブラリは使用していません。show() はビットストリームを手作業で構築し、それを ESP32-S3 の RMT ペリフェラルに渡し、ハードウェアタイミングで再生させます。WS2812 プロトコルはジッタの許容量が非常に小さく、ビジーループでは決して維持できません。

構成要素は小さな関数に分かれています。putBit() は 1 ビットを 1 つの 1.25 µs の RMT シンボルに変換し、putByte() はそれを MSB ファーストで 8 個出力します。各 LED は緑、赤、青の順でデータを受け取ります。sweepStep() は SWEEP_MS ごとに 1 回ストリップ全体を再描画して色の変化がストリップ上をゆっくり進むようにし、pollButton() は KEY をデバウンスして次のパレットエントリを要求します。どちらの関数も loop() から呼び出されるだけでブロックしないため、ボタンを読み取っている間もスイープは動き続けます。

注記

この実験で使用しているライトボードは、サードパーティである CH Maker Ed の WS2812 ボードです。キットの一部ではなく(自分で用意します)、特定のそのボードである必要もありません。このスケッチは標準的な WS2812 ビットストリームを D13 に送るだけなので、D13 に配線された任意の WS2812 ボードは同じように動作します。

ステップ 1. スケッチを作成する

Arduino IDE で File > New Sketch を開き、テンプレートコードを削除して、以下のスケッチを貼り付けます。

アップロードする前に、LED_COUNT をボード上の LED の数に設定します。スケッチの初期値は 8 です。この数だけの LED に対してしかデータを生成しないため、より長いストリップでは LED_COUNT 以降は暗いままで、より短いストリップでは余分なデータはどの LED にも届きません。

Full code
/* SPDX-License-Identifier: MIT */
/* Experiment 3: Button-Switched RGB LED - press KEY and the whole WS2812 strip switches to the next color,
* but the LEDs turn over one at a time: LED0 first, then one more every
* SWEEP_MS, so the change crawls along the strip instead of jumping. The palette
* loops OFF -> RED -> GREEN -> BLUE. The sweep is non-blocking, so a press
* arriving mid-sweep is simply ignored.
* Zero library, core RMT only. Button KEY = D11/GPIO38 (active low), strip = D13.
*/

#include <Arduino.h>
#include <esp32-hal-rmt.h>

/* ── pins ── */
#define PIN_WS2812 40 /* D13, strip data in */
#define PIN_BUTTON 38 /* D11 / KEY, low while pressed */

/* ── strip size and WS2812 bit timing ── */
#define LED_COUNT 8 /* raise if your strip has more LEDs */
#define RMT_TICK_HZ 20000000u /* 20 MHz: one RMT tick is 50 ns */
#define T1H 16 /* 16 * 50 ns = 800 ns high */
#define T1L 9 /* 9 * 50 ns = 450 ns low */
#define T0H 8 /* 8 * 50 ns = 400 ns high */
#define T0L 17 /* 17 * 50 ns = 850 ns low */
#define RESET_US 60 /* low for > 50 us latches the frame */

/* ── behavior ── */
#define SWEEP_MS 60 /* time between two LEDs during a change */
#define DEBOUNCE_MS 10 /* the button must be stable that long */

/* Palette, cycled in order; index 0 is "off". */
static const uint8_t kPalette[][3] = {
{0, 0, 0}, {255, 0, 0}, {0, 255, 0}, {0, 0, 255},
};
#define N_COLOR ((uint8_t)(sizeof(kPalette) / sizeof(kPalette[0])))

/* 24 RMT symbols per LED: 8 bits each of G, R and B. */
static uint8_t sPix[LED_COUNT][3]; /* r, g, b of every LED */
static rmt_data_t sFrame[LED_COUNT * 24]; /* RMT symbols, 24 bits per LED */

/* Sweep state: which palette entry, which LED is next, when it is due. */
static uint8_t gColor = 0; /* palette index being painted */
static uint8_t gNext = LED_COUNT; /* next LED to paint; LED_COUNT = idle */
static unsigned long gStepAt = 0; /* millis() when the next LED is due */

/* One bit = level0/duration0 then level1/duration1, 1.25 us in total. */
static void putBit(rmt_data_t *d, uint8_t b) {
d->duration0 = b ? T1H : T0H;
d->duration1 = b ? T1L : T0L;
d->level0 = 1;
d->level1 = 0;
}

/* Encode 8 bits MSB first and return the next free symbol. */
static rmt_data_t *putByte(rmt_data_t *d, uint8_t v) {
for (int8_t i = 7; i >= 0; i--) putBit(d++, (uint8_t)((v >> i) & 1u));
return d;
}

/* Push the whole strip as GRB, then hold the line low to latch the frame. */
static void show() {
rmt_data_t *d = sFrame;
for (uint8_t n = 0; n < LED_COUNT; n++) {
d = putByte(d, sPix[n][1]); /* G */
d = putByte(d, sPix[n][0]); /* R */
d = putByte(d, sPix[n][2]); /* B */
}
/* One call sends the whole frame; the RMT hardware holds the bit timing. */
rmtWrite(PIN_WS2812, sFrame, (size_t)LED_COUNT * 24, 100);
delayMicroseconds(RESET_US);
}

/* Switch to the next palette color; ignored while a sweep is still running. */
static void nextColor() {
if (gNext < LED_COUNT) return;
gColor = (uint8_t)((gColor + 1) % N_COLOR);
gNext = 0;
gStepAt = millis(); /* the next loop paints LED0 */
}

/* Paint the next LED once its slot has come up. */
static void sweepStep() {
if (gNext >= LED_COUNT) return;
unsigned long now = millis();
if ((long)(now - gStepAt) < 0) return; /* wrap-safe "not yet" */
for (uint8_t k = 0; k < 3; k++) sPix[gNext][k] = kPalette[gColor][k];
show();
gNext++;
gStepAt = now + SWEEP_MS;
}

/* Falling edge = one trigger (raw/stable start as "released", so a button held
* down at power-up counts as one press and then waits for a new edge). */
static void pollButton() {
static bool raw = false, stable = false;
static unsigned long changedAt = 0;
bool pressed = (digitalRead(PIN_BUTTON) == LOW);
if (pressed != raw) { raw = pressed; changedAt = millis(); }
if (raw == stable || millis() - changedAt < DEBOUNCE_MS) return;
stable = raw;
if (stable) nextColor();
}

void setup() {
pinMode(PIN_BUTTON, INPUT_PULLUP);
pinMode(PIN_WS2812, OUTPUT);
digitalWrite(PIN_WS2812, LOW); /* idle low until the first frame */
rmtInit(PIN_WS2812, RMT_TX_MODE, RMT_MEM_NUM_BLOCKS_4, RMT_TICK_HZ);
rmtSetEOT(PIN_WS2812, 0); /* keep the line low between frames */
show(); /* sPix is zero-initialized = dark strip */
}

void loop() {
pollButton();
sweepStep();
delay(1);
}

ステップ 2. スケッチを書き込む

Tools > Board が XIAO_ESP32S3_PLUS になっていることと、Tools > Port にボードが表示されていることを確認し、Upload(→)をクリックします。

ステップ 3. KEY を押す

ボードは最初は消灯しています。KEY を押すたびにパレットが1ステップ進み、LED は一斉ではなく順番に新しい色へ変化します:

  • 1回目の押下:赤
  • 2回目の押下:緑
  • 3回目の押下:青
  • 4回目の押下:再び消灯
ヒント

スイープがまだ進行中のときに押された場合、その押下は無視されます — 最後の LED の色が変わり終わるまで待ってから、もう一度押してください。

よくある質問(FAQ)​

Q1: ロールとピッチは問題ないがヨーがドリフトする​

A: 3つの異なる状況が、いずれもヨーのドリフトとして現れますが、そのうち最初の1つだけが不具合です。

  • ボードが動いているときにゼロ調整した。 6秒間の平均が誤ったオフセットを記録しました。ボードを静止させて、もう一度 KEY を押してください。
  • 最初の18秒以内である。 まだ何も補正されていないため、生のジャイロオフセットがそのまま角度に反映されます。ヘッダー行 roll=deg pitch=deg yaw=deg temp=C が表示されれば、この状態は終了します。
  • このボードではヨーは相対値である。 磁力計がないため、最後にリセットしてからボードがどれだけ回転したかしか分からず、長時間のセッションではドリフトします。ボードが静止している間は、静止トラッカー(STILL_DPS / STILL_MS / BIAS_ALPHA)が残ったレートをバイアスに折り返してヨーを一定に保ちます。動き始めると、もはやそれは役に立ちません。

技術サポート & 製品ディスカッション​

弊社製品をお選びいただきありがとうございます。弊社は、製品をできるだけスムーズにご利用いただけるよう、さまざまなサポートを提供しています。お好みやニーズに合わせて選べる、複数のコミュニケーションチャネルをご用意しています。

Loading Comments...