Home / Tutorials / ESP32 Tutorial / ESP32-S3 TinyML Gesture Recognition with MPU6050 and TensorFlow Lite Micro

ESP32-S3 TinyML Gesture Recognition with MPU6050 and TensorFlow Lite Micro

pcbway

TinyML brings machine learning (ML) models to microcontrollers, so small, low-power boards like the ESP32-S3 can recognize patterns in sensor data without a network connection. In this tutorial, you will train a model that recognizes three hand gestures (wave, punch, and rotate) from an MPU6050 motion sensor and then run it on an ESP32-S3 with TensorFlow Lite for Microcontrollers.

The project covers the full workflow: wiring the sensor, recording labeled gesture data, training and testing the model on your PC, converting it into a C array, and running it on the board. Every sketch and script appears in full, so you won't have to write any missing functions yourself.

What Is TinyML?

TinyML refers to running ML models on microcontrollers and other devices with very little memory, processing power, and energy to spare. With TinyML, an ESP32 can classify sensor readings, detect sounds, or spot unusual vibration on its own.

It helps to separate the two halves of the job. Training happens on your PC, where TensorFlow has the memory and processing power to learn from hundreds of examples. Inference, which means running the finished model on new data, happens on the ESP32-S3. The board never learns anything new; it only applies what the PC taught it, and it does so offline. For a broader look at what the chip family can handle, see the ESP32 AI guide.

Why Use Machine Learning for Gestures?

You could try to detect a punch with a simple rule, such as "forward acceleration above 2 g means a punch." That approach falls apart quickly, though. A wave and a rotation both involve changing acceleration and rotation, people perform each gesture at different speeds, and every new gesture needs another set of hand-tuned rules. Machine learning sidesteps this problem: a small neural network learns the patterns from examples, so adding a gesture only means recording more data and training again.

How the Project Works

The project follows four stages:

  1. Collect: The ESP32-S3 records 1-second motion windows from the MPU6050 and sends them to your PC, where a Python script saves each one with a label.
  2. Train and evaluate: TensorFlow trains a small neural network on those recordings and then tests it on recordings it never saw during training.
  3. Convert: The same Python script converts the model to TensorFlow Lite format and writes it out as a C header file.
  4. Run: The ESP32-S3 records new gestures, feeds them to the model, and prints the result over Serial.

ESP32-S3 TinyML gesture recognition workflow from data collection to on-device inference

The most important design choice is the input window. A single accelerometer reading mostly tells you which way the board is tilted, because gravity dominates it whenever the board moves slowly. Since a wave and a punch can pass through the same tilt, one X/Y/Z sample can't tell them apart. This project therefore gives the model 100 consecutive samples (1 second at 100 Hz) of both acceleration and rotation, which captures how the motion changes over time.

What You Need

This tutorial uses an ESP32-S3 DevKitC-1 N16R8 board and an MPU6050 module, which most sellers list as a GY-521 board.

Besides those two parts, you'll need a breadboard, five jumper wires, and a USB cable that carries data (some cables only charge).

On the software side, the project relies on the versions below. Stick to them while you follow along: TensorFlow and TensorFlow Lite Micro both change their APIs between releases, and version mismatches cause most of the compile errors people hit with older TinyML tutorials.

Software Version Used for
Arduino IDE 2.x Uploading sketches
esp32 board package by Espressif Systems 3.3.13 ESP32-S3 support in the Arduino IDE
Chirale_TensorFLowLite 2.0.0 TensorFlow Lite Micro on the ESP32-S3
Python 3.13 Running the capture and training scripts
TensorFlow / Keras 2.21.0 / 3.15.1 Training and converting the model
ai-edge-litert 2.4.0 Checking the converted model on your PC
pyserial / NumPy 3.5 / 2.5.3 Reading the serial port and handling data

Espressif released version 4.0.0 of the board package in November 2026. Since it's a new major version, stay on 3.3.13 for this project until you've confirmed that the TensorFlow Lite library compiles with 4.x.

Step 1: Wire the MPU6050 to the ESP32-S3

The MPU6050 talks to the ESP32-S3 over I2C, so you only need power, ground, and two signal wires. Make the following connections:

MPU6050 (GY-521) pin ESP32-S3 DevKitC-1 pin
VCC 3V3
GND GND
SDA GPIO8
SCL GPIO9
AD0 GND (sets I2C address 0x68)
XDA, XCL, INT Not connected

MPU6050 GY-521 wired to ESP32-S3 DevKitC-1 GPIO8 and GPIO9 over I2C

Keep these details in mind while you wire it up:

  • Power from 3V3: The GY-521 has its own voltage regulator and I2C pull-up resistors. When you power it from the 3V3 pin, the SDA and SCL lines stay at the ESP32-S3's 3.3 V logic level.
  • GPIO8 and GPIO9: These are the ESP32-S3's default I2C pins in the Arduino core, and both sketches also set them explicitly with Wire.begin(8, 9). The ESP32-S3 pinout shows where they sit on the header.
  • Avoid GPIO35 to GPIO37: On N16R8 boards, the octal PSRAM uses these pins, so they aren't free for the sensor.
  • Keep the sensor fixed: Mount the module firmly on the breadboard and hold the breadboard the same way every time. The model learns the sensor's orientation along with the motion, so a different grip during testing looks like a different gesture.

Step 2: Set Up the Arduino IDE and Python

You'll use the Arduino IDE to program the board and Python on your PC to record data and train the model.

Install the ESP32 Board Package

If you haven't already, install the Arduino IDE. Next, add Espressif's board package:

  1. Open File > Preferences.
  2. Paste the following URL into Additional boards manager URLs and click OK.
https://espressif.github.io/arduino-esp32/package_esp32_index.json
  1. Open Tools > Board > Boards Manager, search for "esp32", and install esp32 by Espressif Systems version 3.3.13.
  2. Under Tools, choose the settings below.
  • Board: ESP32S3 Dev Module
  • Flash Size: 16MB (128Mb)
  • PSRAM: OPI PSRAM (this project doesn't need PSRAM, but it's the correct setting for an N16R8)
  • USB CDC On Boot: Disabled when you use the UART port, Enabled when you use the USB port

The DevKitC-1 has two USB connectors. Plug your cable into the one labeled UART (often COM on third-party boards), which goes through the board's USB-to-UART bridge, and Serial output works with the default settings. The ESP32-S3 getting started guide explains the difference between the two ports in more detail.

Install the TensorFlow Lite Micro Library

At TensorFlow's request, Arduino removed the original Arduino_TensorFlowLite library from the Library Manager, and that library never targeted the ESP32 anyway. This tutorial uses Chirale_TensorFLowLite instead, a port of TensorFlow Lite for Microcontrollers that lists ESP32 support. Its authors include the Arduino Nano ESP32, which also uses an ESP32-S3, among their tested boards.

  1. Open Sketch > Include Library > Manage Libraries.
  2. Search for "Chirale".
  3. Install Chirale_TensorFLowLite version 2.0.0. Note the unusual capital L in "FLow"; that's how the library spells its name.

You don't need an MPU6050 library or any other Arduino library. Both sketches talk to the sensor directly through the Wire library that comes with the board package, so you can see exactly which units and ranges the model receives.

Set Up Python

Create a project folder with the layout below. You'll add each file as you go through the steps.

tinyml-esp32-gesture/
├── collect_imu_data/
│   └── collect_imu_data.ino
├── gesture_inference/
│   ├── gesture_inference.ino
│   └── gesture_model.h      (created by train.py)
└── python/
    ├── capture.py
    ├── train.py
    ├── requirements.txt
    └── data/                (created by capture.py)

Save the following list as python/requirements.txt:

tensorflow==2.21.0
keras==3.15.1
ai-edge-litert==2.4.0
numpy==2.5.3
pyserial==3.5

Then open a terminal in the python folder, create a virtual environment with Python 3.13, and install the packages:

# Windows
py -3.13 -m venv .venv
.venv\Scripts\activate

# macOS and Linux
python3.13 -m venv .venv
source .venv/bin/activate

pip install -r requirements.txt

TensorFlow is a large download, so this step can take a few minutes.

Step 3: Collect Labeled Gesture Data

A model can only be as good as its training data, so this step deserves the most care.

Upload the Data Collection Sketch

Save this sketch as collect_imu_data/collect_imu_data.ino and upload it to the ESP32-S3:

// Gesture data collection for ESP32-S3 + MPU6050
// Waits for motion, records one 1-second window at 100 Hz,
// and prints it over Serial between BEGIN and END markers.

#include <Wire.h>

const int SDA_PIN = 8;   // ESP32-S3 DevKitC-1 default SDA
const int SCL_PIN = 9;   // ESP32-S3 DevKitC-1 default SCL
const uint8_t MPU_ADDR = 0x68;  // AD0 pin low

const int SAMPLE_RATE_HZ = 100;
const int WINDOW_SAMPLES = 100;   // 1 second of data
const unsigned long SAMPLE_PERIOD_US = 1000000UL / SAMPLE_RATE_HZ;

// Motion trigger: start recording when either threshold is crossed
const float ACCEL_TRIGGER_G = 0.35;    // change from 1 g of gravity
const float GYRO_TRIGGER_DPS = 120.0;  // rotation speed

// Sensor ranges set in setupMPU6050(): +/-4 g and +/-500 deg/s
const float ACCEL_LSB_PER_G = 8192.0;
const float GYRO_LSB_PER_DPS = 65.5;

bool writeRegister(uint8_t reg, uint8_t value) {
  Wire.beginTransmission(MPU_ADDR);
  Wire.write(reg);
  Wire.write(value);
  return Wire.endTransmission() == 0;
}

bool setupMPU6050() {
  Wire.beginTransmission(MPU_ADDR);
  if (Wire.endTransmission() != 0) {
    return false;  // no ACK from the sensor
  }
  writeRegister(0x6B, 0x01);  // PWR_MGMT_1: wake up, gyro X clock
  delay(100);
  writeRegister(0x1A, 0x03);  // CONFIG: digital low-pass filter about 44 Hz
  writeRegister(0x19, 9);     // SMPLRT_DIV: 1 kHz / (1 + 9) = 100 Hz
  writeRegister(0x1B, 0x08);  // GYRO_CONFIG: +/-500 deg/s
  writeRegister(0x1C, 0x08);  // ACCEL_CONFIG: +/-4 g
  return true;
}

// Reads acceleration in g and rotation in deg/s
bool readMPU6050(float &ax, float &ay, float &az,
                 float &gx, float &gy, float &gz) {
  Wire.beginTransmission(MPU_ADDR);
  Wire.write(0x3B);  // ACCEL_XOUT_H
  if (Wire.endTransmission(false) != 0) {
    return false;
  }
  if (Wire.requestFrom(MPU_ADDR, (size_t)14) != 14) {
    return false;
  }
  int16_t raw[7];
  for (int i = 0; i < 7; i++) {
    uint8_t high = Wire.read();
    uint8_t low = Wire.read();
    raw[i] = (int16_t)((high << 8) | low);
  }
  // raw[3] is the temperature reading, which this project ignores
  ax = raw[0] / ACCEL_LSB_PER_G;
  ay = raw[1] / ACCEL_LSB_PER_G;
  az = raw[2] / ACCEL_LSB_PER_G;
  gx = raw[4] / GYRO_LSB_PER_DPS;
  gy = raw[5] / GYRO_LSB_PER_DPS;
  gz = raw[6] / GYRO_LSB_PER_DPS;
  return true;
}

bool motionDetected(float ax, float ay, float az,
                    float gx, float gy, float gz) {
  float accelMagnitude = sqrt(ax * ax + ay * ay + az * az);
  float gyroMagnitude = sqrt(gx * gx + gy * gy + gz * gz);
  return fabs(accelMagnitude - 1.0) > ACCEL_TRIGGER_G ||
         gyroMagnitude > GYRO_TRIGGER_DPS;
}

void setup() {
  Serial.begin(115200);
  delay(1000);
  Wire.begin(SDA_PIN, SCL_PIN);
  Wire.setClock(400000);

  if (!setupMPU6050()) {
    Serial.println("ERROR: MPU6050 not found. Check wiring and address.");
    while (true) {
      delay(1000);
    }
  }
  Serial.println("READY: perform a gesture to record it");
}

void loop() {
  float ax, ay, az, gx, gy, gz;
  if (!readMPU6050(ax, ay, az, gx, gy, gz)) {
    Serial.println("ERROR: sensor read failed");
    delay(100);
    return;
  }
  if (!motionDetected(ax, ay, az, gx, gy, gz)) {
    delay(10);
    return;
  }

  Serial.println("BEGIN");
  Serial.println("ax,ay,az,gx,gy,gz");
  unsigned long nextSample = micros();
  for (int i = 0; i < WINDOW_SAMPLES; i++) {
    while ((long)(micros() - nextSample) < 0) {
      // wait for the next 10 ms time slot
    }
    nextSample += SAMPLE_PERIOD_US;
    readMPU6050(ax, ay, az, gx, gy, gz);
    Serial.printf("%.4f,%.4f,%.4f,%.2f,%.2f,%.2f\n", ax, ay, az, gx, gy, gz);
  }
  Serial.println("END");

  delay(1000);  // pause so one gesture creates one recording
}

How the Collection Sketch Works

The sketch does five things:

  • Sets up the sensor: setupMPU6050() wakes the MPU6050 and selects a ±4 g accelerometer range, a ±500 °/s gyroscope range, a 44 Hz low-pass filter, and a 100 Hz sample rate.
  • Converts to real units: readMPU6050() reads all six axes in one I2C transfer and divides the raw counts by the datasheet scale factors (8192 counts per g and 65.5 counts per °/s).
  • Waits for motion: motionDetected() returns true once total acceleration moves 0.35 g away from 1 g (gravity alone) or rotation passes 120 °/s. As a result, the sketch ignores the board while it sits still.
  • Records one window: It then takes 100 samples, one every 10 ms using micros(), and prints them as CSV lines between BEGIN and END markers.
  • Pauses: A 1-second delay afterward keeps the tail end of one gesture from starting a second recording.

To check it, open the Serial Monitor at 115200 baud and move the board. Each movement should produce a block of 100 lines. Close the Serial Monitor before the next step, because only one program can use the serial port at a time.

Record Each Gesture With Python

Next, save this script as python/capture.py. It listens to the serial port and saves each BEGIN/END block as its own CSV file:

"""Save labeled gesture recordings from the ESP32-S3 serial port.

Example:
    python capture.py --port COM5 --gesture wave --count 40
"""
import argparse
import pathlib

import serial

EXPECTED_ROWS = 100
HEADER = "ax,ay,az,gx,gy,gz"


def next_index(folder, gesture):
    existing = sorted(folder.glob(f"{gesture}_*.csv"))
    if not existing:
        return 1
    return int(existing[-1].stem.split("_")[-1]) + 1


def read_recordings(lines):
    """Yield one list of CSV rows for each BEGIN ... END block."""
    rows = None
    for line in lines:
        if line == "BEGIN":
            rows = []
        elif line == "END" and rows is not None:
            yield rows
            rows = None
        elif rows is not None and line != HEADER:
            rows.append(line)
        elif line.startswith(("READY", "ERROR")):
            print(line)


def serial_lines(port, baud):
    with serial.Serial(port, baud, timeout=1) as ser:
        while True:
            line = ser.readline().decode("utf-8", errors="ignore").strip()
            if line:
                yield line


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--port", required=True, help="e.g. COM5 or /dev/ttyUSB0")
    parser.add_argument("--gesture", required=True, help="label, e.g. wave")
    parser.add_argument("--count", type=int, default=40)
    parser.add_argument("--baud", type=int, default=115200)
    parser.add_argument("--data-dir", default="data")
    args = parser.parse_args()

    folder = pathlib.Path(args.data_dir) / args.gesture
    folder.mkdir(parents=True, exist_ok=True)
    index = next_index(folder, args.gesture)
    saved = 0

    print(f"Perform the '{args.gesture}' gesture {args.count} times.")
    for rows in read_recordings(serial_lines(args.port, args.baud)):
        if len(rows) != EXPECTED_ROWS:
            print(f"Skipped a recording with {len(rows)} rows")
            continue
        path = folder / f"{args.gesture}_{index:03d}.csv"
        path.write_text(HEADER + "\n" + "\n".join(rows) + "\n")
        saved += 1
        index += 1
        print(f"Saved {path} ({saved}/{args.count})")
        if saved >= args.count:
            break


if __name__ == "__main__":
    main()

Run it once per gesture, replacing COM5 with the port the Arduino IDE shows for your board (for example, /dev/ttyUSB0 on Linux):

python capture.py --port COM5 --gesture wave --count 40
python capture.py --port COM5 --gesture punch --count 40
python capture.py --port COM5 --gesture rotate --count 40

For each run, perform the gesture whenever you're ready and wait for the "Saved" message before the next one. The script writes files such as data/wave/wave_001.csv and skips any incomplete recording. If you run it again for the same gesture, it continues the numbering instead of overwriting earlier files.

How Much Data Do You Need?

These guidelines make the difference between a model that works on your desk and one that only works on the training data:

  • Quantity: Aim for 30 to 50 recordings per gesture. The training script stops with a message if any gesture has fewer than 10.
  • Variety: Spread the recordings over two or three sessions and vary the speed and size of each gesture a little, the way you'll actually perform it later.
  • Consistency: Hold the board with the same grip and orientation that you plan to use during testing.
  • An optional "other" class: Record 30 or more random movements, such as picking up the board or setting it down, with --gesture other. Because the training script reads labels from folder names, it picks up the new class without code changes. The model then has a place to put motions that aren't real gestures.
  • No duplicates: Don't copy recordings between files. The training script keeps each recording in exactly one of its training, validation, or test sets, and a duplicate would quietly leak test data into training.

Step 4: Train and Evaluate the Model

With the data recorded, save the training script as python/train.py:

"""Train, evaluate, and convert the gesture model for the ESP32-S3.

Reads data/<gesture>/*.csv, trains a small neural network, prints a
confusion matrix for held-out recordings, and writes:
  gesture_model.keras   the trained Keras model
  gesture_model.tflite  the TensorFlow Lite model
  ../gesture_inference/gesture_model.h  the model as a C array
"""
import argparse
import pathlib

import numpy as np
import tensorflow as tf
from tensorflow import keras
from ai_edge_litert.interpreter import Interpreter

WINDOW_SAMPLES = 100
CHANNELS = 6          # ax, ay, az, gx, gy, gz
ACCEL_SCALE = 4.0     # +/-4 g range  -> -1.0 to 1.0
GYRO_SCALE = 500.0    # +/-500 deg/s  -> -1.0 to 1.0
SEED = 42


def load_recordings(data_dir):
    labels = sorted(p.name for p in pathlib.Path(data_dir).iterdir() if p.is_dir())
    windows, targets = [], []
    for class_id, label in enumerate(labels):
        files = sorted((pathlib.Path(data_dir) / label).glob("*.csv"))
        for path in files:
            values = np.loadtxt(path, delimiter=",", skiprows=1, dtype=np.float32)
            if values.shape != (WINDOW_SAMPLES, CHANNELS):
                print(f"Skipping {path}: shape {values.shape}")
                continue
            windows.append(values)
            targets.append(class_id)
        print(f"{label}: {targets.count(class_id)} recordings")
    return np.array(windows), np.array(targets), labels


def normalize(windows):
    scaled = windows.copy()
    scaled[:, :, 0:3] /= ACCEL_SCALE
    scaled[:, :, 3:6] /= GYRO_SCALE
    # Flatten each window: sample 0 (ax..gz), sample 1 (ax..gz), ...
    return scaled.reshape(len(scaled), WINDOW_SAMPLES * CHANNELS)


def split_by_recording(targets, val_fraction=0.15, test_fraction=0.15):
    """Split whole recordings per class so no recording lands in two sets."""
    rng = np.random.default_rng(SEED)
    train, val, test = [], [], []
    for class_id in np.unique(targets):
        idx = rng.permutation(np.where(targets == class_id)[0])
        n_test = max(1, round(len(idx) * test_fraction))
        n_val = max(1, round(len(idx) * val_fraction))
        test += list(idx[:n_test])
        val += list(idx[n_test:n_test + n_val])
        train += list(idx[n_test + n_val:])
    return np.array(train), np.array(val), np.array(test)


def build_model(num_classes):
    return keras.Sequential([
        keras.Input(shape=(WINDOW_SAMPLES * CHANNELS,)),
        keras.layers.Dense(32, activation="relu"),
        keras.layers.Dropout(0.2),
        keras.layers.Dense(16, activation="relu"),
        keras.layers.Dense(num_classes, activation="softmax"),
    ])


def print_confusion_matrix(true_ids, predicted_ids, labels):
    matrix = np.zeros((len(labels), len(labels)), dtype=int)
    for t, p in zip(true_ids, predicted_ids):
        matrix[t, p] += 1
    width = max(len(name) for name in labels) + 2
    print("Rows = actual gesture, columns = predicted gesture")
    print(" " * width + "".join(f"{name:>{width}}" for name in labels))
    for name, row in zip(labels, matrix):
        print(f"{name:<{width}}" + "".join(f"{n:>{width}}" for n in row))


def write_c_header(tflite_model, labels, path):
    lines = [
        "// Generated by train.py. Do not edit by hand.",
        "#pragma once",
        "",
        f"const int kWindowSamples = {WINDOW_SAMPLES};",
        f"const int kChannels = {CHANNELS};",
        f"const float kAccelScale = {ACCEL_SCALE}f;",
        f"const float kGyroScale = {GYRO_SCALE}f;",
        f"const int kNumLabels = {len(labels)};",
        "const char* const kLabels[kNumLabels] = {"
        + ", ".join(f'"{name}"' for name in labels) + "};",
        "",
        f"const unsigned int g_gesture_model_len = {len(tflite_model)};",
        "alignas(16) const unsigned char g_gesture_model[] = {",
    ]
    for start in range(0, len(tflite_model), 12):
        chunk = tflite_model[start:start + 12]
        lines.append("  " + ", ".join(f"0x{b:02x}" for b in chunk) + ",")
    lines.append("};")
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text("\n".join(lines) + "\n")


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--data-dir", default="data")
    parser.add_argument("--header", default="../gesture_inference/gesture_model.h")
    args = parser.parse_args()

    keras.utils.set_random_seed(SEED)
    windows, targets, labels = load_recordings(args.data_dir)
    if len(labels) < 2 or np.bincount(targets).min() < 10:
        raise SystemExit("Record at least 10 examples (30+ recommended) for 2+ gestures.")

    x = normalize(windows)
    train_idx, val_idx, test_idx = split_by_recording(targets)
    print(f"Train {len(train_idx)}, validation {len(val_idx)}, test {len(test_idx)} recordings")

    model = build_model(len(labels))
    model.compile(optimizer="adam",
                  loss="sparse_categorical_crossentropy",
                  metrics=["accuracy"])
    model.fit(x[train_idx], targets[train_idx],
              validation_data=(x[val_idx], targets[val_idx]),
              epochs=300, batch_size=16, verbose=0,
              callbacks=[keras.callbacks.EarlyStopping(
                  monitor="val_loss", patience=30, restore_best_weights=True)])

    _, val_acc = model.evaluate(x[val_idx], targets[val_idx], verbose=0)
    _, test_acc = model.evaluate(x[test_idx], targets[test_idx], verbose=0)
    print(f"Validation accuracy: {val_acc:.3f}")
    print(f"Test accuracy:       {test_acc:.3f}")
    predicted = np.argmax(model.predict(x[test_idx], verbose=0), axis=1)
    print_confusion_matrix(targets[test_idx], predicted, labels)
    model.save("gesture_model.keras")

    # Convert to a float32 TensorFlow Lite model
    converter = tf.lite.TFLiteConverter.from_keras_model(model)
    tflite_model = converter.convert()
    pathlib.Path("gesture_model.tflite").write_bytes(tflite_model)

    # Check that the converted model agrees with the Keras model
    interpreter = Interpreter(model_content=tflite_model)
    interpreter.allocate_tensors()
    inp = interpreter.get_input_details()[0]
    out = interpreter.get_output_details()[0]
    tflite_predicted = []
    for row in x[test_idx]:
        interpreter.set_tensor(inp["index"], row[np.newaxis, :])
        interpreter.invoke()
        tflite_predicted.append(int(np.argmax(interpreter.get_tensor(out["index"]))))
    agreement = np.mean(np.array(tflite_predicted) == predicted)
    print(f"TFLite vs. Keras agreement on test set: {agreement:.3f}")

    write_c_header(tflite_model, labels, pathlib.Path(args.header))
    print(f"Model size: {len(tflite_model)} bytes")
    print(f"Wrote {args.header}")


if __name__ == "__main__":
    main()

Run it from the python folder:

python train.py

TensorFlow prints a few informational messages while it loads; you can ignore those.

What the Training Script Does

  • Normalization: normalize() divides acceleration by 4 and rotation by 500, so every input falls between -1 and 1. The script also writes these two constants into the model header, so the ESP32-S3 scales its data exactly the same way.
  • Feature order: Each window becomes 600 numbers in a fixed order: ax, ay, az, gx, gy, and gz for sample 0, then the same six values for sample 1, and so on. The inference sketch fills the model's input in that same order.
  • Splitting: split_by_recording() puts about 70% of each gesture's recordings into training, 15% into validation, and 15% into testing. It moves whole recordings, and a fixed random seed makes the split repeatable.
  • Training: The model trains for up to 300 epochs, but early stopping ends training once validation loss stops improving for 30 epochs and then restores the best weights.
  • Evaluation: The script prints validation accuracy, test accuracy, and a confusion matrix for the test recordings.
  • Conversion check: After converting the model, the script runs the TensorFlow Lite version on the test set with the LiteRT interpreter and reports how often it agrees with the original Keras model. You should see 1.000.

Why This Model Architecture?

The network is deliberately small. Its 600 inputs feed a Dense layer with 32 neurons, a Dropout layer, a second Dense layer with 16 neurons, and an output layer with one neuron per gesture. Here's why each part is there:

  • Dense layers: Every neuron in the first layer sees the whole 1-second window, so the network can learn the timing and shape of each gesture. They also convert to a single TensorFlow Lite operation, FULLY_CONNECTED, which keeps the ESP32 code simple.
  • ReLU activation: This activation lets the network learn non-linear patterns while costing almost nothing to compute, and the converter merges it into the Dense layers.
  • Dropout: During training, Dropout randomly switches off 20% of the first layer's outputs, which reduces overfitting on a small dataset. It has no effect after conversion.
  • Softmax output: The last layer turns the network's outputs into one score per gesture, and the scores always add up to 1.

For three gestures, the model has about 19,800 weights and converts to an 81 KB TensorFlow Lite file. A one-dimensional convolutional network could learn time patterns with fewer weights, but it needs more operations on the microcontroller and more tuning. For a handful of distinct gestures, the dense model is the simpler place to start. If its accuracy stops improving as you add data, try a convolutional model next.

How to Read the Results

Training accuracy says very little on its own, since the model has already seen those recordings. Instead, focus on test accuracy, which comes from recordings the model never trained on, and on the confusion matrix. Each row of the matrix shows an actual gesture, while each column shows what the model predicted. Numbers off the diagonal reveal which gestures the model mixes up, so you know where to record more examples or make two gestures more distinct.

Keep the test set's size in mind too. With 40 recordings per gesture, only 6 of each end up in testing, so a single mistake moves test accuracy by several percent. The real verdict comes when you try the gestures on the board.

Step 5: Convert the Model to a C Array

An Arduino sketch can't open the gesture_model.tflite file sitting on your PC, so the model has to become part of the firmware. That's why train.py ends by writing gesture_model.h straight into the gesture_inference sketch folder. The top of the generated file looks like this:

// Generated by train.py. Do not edit by hand.
#pragma once

const int kWindowSamples = 100;
const int kChannels = 6;
const float kAccelScale = 4.0f;
const float kGyroScale = 500.0f;
const int kNumLabels = 3;
const char* const kLabels[kNumLabels] = {"punch", "rotate", "wave"};

const unsigned int g_gesture_model_len = 81436;
alignas(16) const unsigned char g_gesture_model[] = {
  0x1c, 0x00, 0x00, 0x00, 0x54, 0x46, 0x4c, 0x33, 0x14, 0x00, 0x20, 0x00,
  // ... about 81,000 more bytes ...
};

The alignas(16) keyword aligns the array the way TensorFlow Lite Micro expects, and const keeps all 81 KB in flash instead of RAM. Because the labels and scaling constants come from the same training run as the model, they can't drift out of sync with it. Whenever you add recordings or gestures, run train.py again and re-upload the inference sketch; the sketch reads the new label list from the header automatically.

On Linux and macOS, the command xxd -i gesture_model.tflite produces a similar byte array. If you use it, though, you'll have to add the labels and scaling constants by hand.

Should You Quantize the Model?

Quantization stores the weights as 8-bit integers instead of 32-bit floats. It shrinks a model to roughly a quarter of its size and often speeds it up on chips without floating-point hardware. This project keeps the float32 model for three reasons: the ESP32-S3 has a hardware floating-point unit, an 81 KB model fits easily in the N16R8's 16 MB of flash, and float inputs avoid an extra scaling step that's easy to get wrong. Quantization becomes worth adding when you move to a much larger model or a board with less memory. If you do, the inference sketch's type check will remind you to update its input and output handling.

Step 6: Run Gesture Recognition on the ESP32-S3

Now for the part that runs on the board. Save this sketch as gesture_inference/gesture_inference.ino, in the same folder as the generated gesture_model.h:

// Gesture recognition on ESP32-S3 + MPU6050 with TensorFlow Lite Micro
// Waits for motion, records a 1-second window at 100 Hz,
// runs the model, and prints the predicted gesture.

#include <Wire.h>
#include <Chirale_TensorFlowLite.h>
#include "tensorflow/lite/micro/micro_interpreter.h"
#include "tensorflow/lite/micro/micro_mutable_op_resolver.h"
#include "tensorflow/lite/schema/schema_generated.h"
#include "gesture_model.h"  // generated by train.py

const int SDA_PIN = 8;
const int SCL_PIN = 9;
const uint8_t MPU_ADDR = 0x68;

const int SAMPLE_RATE_HZ = 100;
const unsigned long SAMPLE_PERIOD_US = 1000000UL / SAMPLE_RATE_HZ;
const float ACCEL_TRIGGER_G = 0.35;
const float GYRO_TRIGGER_DPS = 120.0;
const float ACCEL_LSB_PER_G = 8192.0;
const float GYRO_LSB_PER_DPS = 65.5;

// Predictions below this score print as "unknown"
const float CONFIDENCE_THRESHOLD = 0.80;

// Working memory for the model's tensors
constexpr int kTensorArenaSize = 16 * 1024;
alignas(16) static uint8_t tensor_arena[kTensorArenaSize];

tflite::MicroInterpreter* interpreter = nullptr;
TfLiteTensor* input = nullptr;
TfLiteTensor* output = nullptr;

bool writeRegister(uint8_t reg, uint8_t value) {
  Wire.beginTransmission(MPU_ADDR);
  Wire.write(reg);
  Wire.write(value);
  return Wire.endTransmission() == 0;
}

bool setupMPU6050() {
  Wire.beginTransmission(MPU_ADDR);
  if (Wire.endTransmission() != 0) {
    return false;
  }
  writeRegister(0x6B, 0x01);  // wake up, gyro X clock
  delay(100);
  writeRegister(0x1A, 0x03);  // low-pass filter about 44 Hz
  writeRegister(0x19, 9);     // 100 Hz sample rate
  writeRegister(0x1B, 0x08);  // +/-500 deg/s
  writeRegister(0x1C, 0x08);  // +/-4 g
  return true;
}

bool readMPU6050(float &ax, float &ay, float &az,
                 float &gx, float &gy, float &gz) {
  Wire.beginTransmission(MPU_ADDR);
  Wire.write(0x3B);
  if (Wire.endTransmission(false) != 0) {
    return false;
  }
  if (Wire.requestFrom(MPU_ADDR, (size_t)14) != 14) {
    return false;
  }
  int16_t raw[7];
  for (int i = 0; i < 7; i++) {
    uint8_t high = Wire.read();
    uint8_t low = Wire.read();
    raw[i] = (int16_t)((high << 8) | low);
  }
  ax = raw[0] / ACCEL_LSB_PER_G;
  ay = raw[1] / ACCEL_LSB_PER_G;
  az = raw[2] / ACCEL_LSB_PER_G;
  gx = raw[4] / GYRO_LSB_PER_DPS;
  gy = raw[5] / GYRO_LSB_PER_DPS;
  gz = raw[6] / GYRO_LSB_PER_DPS;
  return true;
}

bool motionDetected(float ax, float ay, float az,
                    float gx, float gy, float gz) {
  float accelMagnitude = sqrt(ax * ax + ay * ay + az * az);
  float gyroMagnitude = sqrt(gx * gx + gy * gy + gz * gz);
  return fabs(accelMagnitude - 1.0) > ACCEL_TRIGGER_G ||
         gyroMagnitude > GYRO_TRIGGER_DPS;
}

void stopWithError(const char* message) {
  Serial.print("ERROR: ");
  Serial.println(message);
  while (true) {
    delay(1000);
  }
}

void setupModel() {
  const tflite::Model* model = tflite::GetModel(g_gesture_model);
  if (model->version() != TFLITE_SCHEMA_VERSION) {
    stopWithError("model schema version does not match the library");
  }

  // Register only the operations this model uses
  static tflite::MicroMutableOpResolver<2> resolver;
  if (resolver.AddFullyConnected() != kTfLiteOk ||
      resolver.AddSoftmax() != kTfLiteOk) {
    stopWithError("could not register model operations");
  }

  static tflite::MicroInterpreter static_interpreter(
      model, resolver, tensor_arena, kTensorArenaSize);
  interpreter = &static_interpreter;

  if (interpreter->AllocateTensors() != kTfLiteOk) {
    stopWithError("AllocateTensors() failed, increase kTensorArenaSize");
  }

  input = interpreter->input(0);
  output = interpreter->output(0);
  if (input->type != kTfLiteFloat32 || output->type != kTfLiteFloat32) {
    stopWithError("this sketch expects a float32 model");
  }
  if (input->dims->size != 2 ||
      input->dims->data[1] != kWindowSamples * kChannels) {
    stopWithError("model input size does not match the sensor window");
  }
  if (output->dims->size != 2 || output->dims->data[1] != kNumLabels) {
    stopWithError("model output size does not match the label list");
  }

  Serial.printf("Model size: %u bytes\n", g_gesture_model_len);
  Serial.printf("Tensor arena used: %u of %d bytes\n",
                (unsigned)interpreter->arena_used_bytes(), kTensorArenaSize);
}

void setup() {
  Serial.begin(115200);
  delay(1000);
  Wire.begin(SDA_PIN, SCL_PIN);
  Wire.setClock(400000);

  if (!setupMPU6050()) {
    stopWithError("MPU6050 not found, check wiring and address");
  }
  setupModel();
  Serial.println("READY: perform a gesture");
}

void loop() {
  float ax, ay, az, gx, gy, gz;
  if (!readMPU6050(ax, ay, az, gx, gy, gz)) {
    Serial.println("ERROR: sensor read failed");
    delay(100);
    return;
  }
  if (!motionDetected(ax, ay, az, gx, gy, gz)) {
    delay(10);
    return;
  }

  // Record one window straight into the input tensor,
  // scaled exactly like normalize() in train.py
  float* features = input->data.f;
  unsigned long nextSample = micros();
  for (int i = 0; i < kWindowSamples; i++) {
    while ((long)(micros() - nextSample) < 0) {
    }
    nextSample += SAMPLE_PERIOD_US;
    readMPU6050(ax, ay, az, gx, gy, gz);
    features[i * kChannels + 0] = ax / kAccelScale;
    features[i * kChannels + 1] = ay / kAccelScale;
    features[i * kChannels + 2] = az / kAccelScale;
    features[i * kChannels + 3] = gx / kGyroScale;
    features[i * kChannels + 4] = gy / kGyroScale;
    features[i * kChannels + 5] = gz / kGyroScale;
  }

  unsigned long start = micros();
  TfLiteStatus status = interpreter->Invoke();
  unsigned long inferenceTime = micros() - start;
  if (status != kTfLiteOk) {
    Serial.println("ERROR: Invoke() failed");
    return;
  }

  int best = 0;
  for (int i = 0; i < kNumLabels; i++) {
    Serial.printf("%s %.2f  ", kLabels[i], output->data.f[i]);
    if (output->data.f[i] > output->data.f[best]) {
      best = i;
    }
  }
  if (output->data.f[best] >= CONFIDENCE_THRESHOLD) {
    Serial.printf("-> %s", kLabels[best]);
  } else {
    Serial.print("-> unknown");
  }
  Serial.printf(" (%lu us)\n", inferenceTime);

  delay(1000);  // ignore the end of the same gesture
}

How the Inference Sketch Works

The sensor code matches the collection sketch, so the model receives data recorded exactly like its training data. On the TensorFlow Lite Micro side, the sketch works as follows:

  • Model check: tflite::GetModel() reads the array from flash, and the sketch confirms that its schema version matches the library.
  • Operation resolver: MicroMutableOpResolver<2> registers FULLY_CONNECTED and SOFTMAX, the only two operations in the converted model. Registering just what the model needs keeps the firmware smaller.
  • Tensor arena: The 16 KB tensor_arena buffer holds the model's input, output, and intermediate values. If AllocateTensors() fails, the sketch stops with a clear message.
  • Type and shape checks: setupModel() confirms the model uses float32 and that its input and output sizes match the header. These checks catch a stale header or a quantized model before they produce nonsense.
  • Matching input: loop() writes each new sample straight into the input tensor, divided by kAccelScale or kGyroScale and in the same order train.py used.
  • Inference and timing: The sketch checks the result of Invoke() and times it with micros().
  • Unknown results: If the top score is below 0.80, the sketch prints "unknown" instead of a gesture.

That last threshold needs one caveat. Softmax scores always add up to 1, so the model always favors some gesture, even for a random bump. The threshold filters out uncertain predictions, but it isn't a true "none of the above" detector. For that job, the optional "other" class from Step 3 works much better.

If you've used older TensorFlow Lite examples, you may notice two missing pieces. Newer TensorFlow Lite Micro releases dropped MicroErrorReporter, so the interpreter now takes four arguments instead of five. The upstream project has also removed AllOpsResolver, which makes registering operations one by one the approach that keeps working as the library evolves.

Upload and Test

  1. Open gesture_inference.ino and confirm that gesture_model.h appears as a second tab in the Arduino IDE.
  2. Select the board settings from Step 2 and the correct port, then upload.
  3. Open the Serial Monitor at 115200 baud. You should see the model size, the tensor arena usage, and a READY line.
  4. Perform each gesture with the same grip you used while recording.

Every prediction prints one line with the score for each gesture, the result, and the inference time in microseconds.

Measure Memory and Inference Time

Since the sketch reports its own resource use, you can measure your setup directly instead of relying on someone else's numbers:

  • Flash: The Arduino IDE's compile summary shows total program storage, and the model array accounts for about 81 KB of it.
  • Tensor arena: The "Tensor arena used" line comes from arena_used_bytes(). This model needs only a few kilobytes, so the 16 KB arena leaves plenty of headroom. You can shrink kTensorArenaSize to about 1 KB above the reported value to free RAM, or raise it for a bigger model.
  • Inference time: Each prediction ends with the time Invoke() took. For a model this size, expect it to be tiny compared with the 1-second recording window, which dominates the delay you notice.

Neither the model nor the arena needs PSRAM. Larger models, such as audio or image classifiers, can place their tensor arena in PSRAM instead; the ESP32-S3 PSRAM guide shows how to enable and use it.

Troubleshooting

Most problems with this project fall into a few groups. Use this table to find the likely cause:

Problem Likely cause Fix
"ERROR: MPU6050 not found" Loose wire, SDA and SCL swapped, or AD0 pulled high Check the wiring table. If AD0 connects to 3.3 V, change MPU_ADDR to 0x69 in both sketches.
Chirale_TensorFlowLite.h: No such file or directory Library not installed Install Chirale_TensorFLowLite 2.0.0 from the Library Manager.
'g_gesture_model' was not declared, or gesture_model.h is missing Header not generated, or saved in the wrong folder Run train.py from the python folder and check that gesture_inference/gesture_model.h exists.
Errors about MicroErrorReporter or the MicroInterpreter constructor Code copied from an older tutorial Use the sketch above, which uses the four-argument constructor.
"AllocateTensors() failed, increase kTensorArenaSize" Tensor arena too small for the model Raise kTensorArenaSize, for example to 32 * 1024.
Didn't find op for builtin opcode The model uses an operation the resolver doesn't register, typically after a model change Add the missing operation to the resolver and raise the number in MicroMutableOpResolver<2>.
"model input size does not match the sensor window" The header comes from a model with a different window or channel count Run train.py again and re-upload the sketch.
Nothing prints when you move the board Wrong port or USB CDC setting, or trigger thresholds too high Use the UART port at 115200 baud, then try lowering ACCEL_TRIGGER_G in both sketches.
capture.py can't open the port The Serial Monitor still has it open Close the Serial Monitor and run the script again.
Good test accuracy, but poor results on the board Different grip or orientation, or too little variety in the data Record more data in several sessions, holding the board the way you test it.
Almost every result is "unknown" Gestures differ from the training data, or the threshold is too strict Look at the printed scores, record more examples, and lower CONFIDENCE_THRESHOLD only slightly.

Frequently Asked Questions

Can the ESP32-S3 train the model by itself?

No. TensorFlow Lite for Microcontrollers only runs inference, so training stays on your PC. The ESP32-S3 just collects data and runs the finished model.

Will this project work on the original ESP32?

The sketches only depend on the Wire library and TensorFlow Lite Micro, so they should carry over to an original ESP32 if you change SDA_PIN and SCL_PIN to 21 and 22. Test it yourself first, since the library's authors don't list the original ESP32 among their tested boards.

Do I need PSRAM for TinyML on the ESP32-S3?

Not for this project. The model lives in flash, and the tensor arena fits comfortably in internal RAM. PSRAM starts to matter for larger models that process audio or camera images.

How do I add a new gesture?

Record it with capture.py under a new name, run train.py again, and re-upload the inference sketch. The generated header carries the new label list, so you don't need to edit the sketch.

Why does the model need 100 samples instead of one reading?

One reading only captures the board's tilt at a single instant. Gestures like a wave or a punch are defined by how acceleration and rotation change over time, and a 1-second window gives the model that history.

Summary

  • TinyML splits the work: your PC trains the model, and the ESP32-S3 runs it offline.
  • Dynamic gestures need a time window, so this project feeds the model 100 samples of acceleration and rotation.
  • Splitting data by recording and judging the model by test accuracy and a confusion matrix gives an honest picture of its performance.
  • The generated header keeps the model, labels, and scaling constants together, so the board processes data exactly like the training script did.
  • The inference sketch checks every TensorFlow Lite Micro step and reports its own memory use and inference time.

Ready for more? Add voice control with voice command recognition on the ESP32 with TinyML, or try another TensorFlow Lite project in Getting Started with TensorFlow Lite on ESP32.