บทความ: สอนใช้งาน ESP32-S3 กับ TinyML Machine Learning บนไมโครคอนโทรลเลอร์

เรียนรู้วิธีนำ Machine Learning มาใช้บน ESP32-S3 ด้วย TensorFlow Lite Micro พร้อมตัวอย่างโค้ดและคำอธิบายภาษาไทย

📅 8 มีนาคม 2026⏱️ 15 นาที🎯 ระดับกลาง

ภาพรวม TinyML คืออะไร?

TinyML (Tiny Machine Learning) เป็นเทคโนโลยีที่ช่วยให้เราสามารถรันโมเดล Machine Learning บนอุปกรณ์ที่มีทรัพยากรจำกัด เช่น ไมโครคอนโทรลเลอร์ ได้ โดยใช้ TensorFlow Lite Micro ซึ่งเป็นเวอร์ชันที่เล็กและเบาเป็นพิเศษ

ESP32-S3 มีความสามารถด้าน AI ที่น่าสนใจ:

  • ❄️ AI Accelerator: มีหน่วยประมวลผลพิเศษสำหรับ Neural Network
  • 🧠 512KB SRAM: หน่วยความจำเพียงพอสำหรับโมเดลขนาดเล็ก
  • 240MHz Dual Core: ประมวลผลได้รวดเร็ว
  • 🔌 USB Native: ต่อเชื่อมต่อกับคอมพิวเตอร์ได้ง่าย

💡 เกร็ดความรู้: TinyML สามารถใช้งานได้แม้กระทั่งบนไมโครคอนโทรลเลอร์ที่มี RAM เพียง 256KB แต่ ESP32-S3 มี 512KB ทำให้สามารถรันโมเดลที่ซับซ้อนขึ้นได้

อุปกรณ์ที่ต้องใช้

Hardware

  • ESP32-S3 Dev Board: เช่น ESP32-S3-DevKitC-1 (~฿250)
  • USB-C Cable: สำหรับเชื่อมต่อกับคอมพิวเตอร์
  • Sensors (Optional): Camera, Microphone หรือ Sensor อื่นๆ

Software

  • Arduino IDE 2.x หรือ PlatformIO
  • ESP32-S3 Board Package (ติดตั้งผ่าน Board Manager)
  • TensorFlow Lite for Microcontrollers Library

การติดตั้งซอฟต์แวร์

ขั้นตอนที่ 1: ติดตั้ง Board Support

เปิด Arduino IDE แล้วไปที่ File > Preferences และเพิ่ม URL นี้ใน "Additional Boards Manager URLs":

https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json

ขั้นตอนที่ 2: ติดตั้ง ESP32 Board

  1. ไปที่ Tools > Board > Boards Manager
  2. ค้นหา "esp32"
  3. ติดตั้ง "esp32 by Espressif Systems"

ขั้นตอนที่ 3: ติดตั้ง TensorFlow Lite Library

  1. ไปที่ Sketch > Include Library > Manage Libraries
  2. ค้นหา "TensorFlow Lite"
  3. ติดตั้ง "TensorFlow Lite for Microcontrollers"

โมเดลแรกกับ ESP32-S3: Hello World

เริ่มต้นด้วยการสร้างโมเดล Machine Learning ง่ายๆ ที่ทำนายค่า sin(x) เพื่อเรียนรู้พื้นฐาน

โค้ดตัวอย่าง: โมเดลพยากรณ์ค่า Sin

// รวม Library ที่จำเป็น
#include <TensorFlowLite.h>
#include <tensorflow/lite/experimental/micro/kernels/micro_ops.h>
#include <tensorflow/lite/experimental/micro/micro_error_reporter.h>
#include <tensorflow/lite/experimental/micro/micro_interpreter.h>
#include <tensorflow/lite/schema/schema_generated.h>
#include <tensorflow/lite/version.h>

// รวมไฟล์โมเดลที่แปลงแล้ว
#include "sin_model_data.h"

// ตั้งค่า Tensor Arena (พื้นที่หน่วยความจำสำหรับโมเดล)
constexpr int kTensorArenaSize = 8 * 1024;
uint8_t tensor_arena[kTensorArenaSize];

// สร้าง Error Reporter
tflite::MicroErrorReporter micro_error_reporter;
tflite::ErrorReporter* error_reporter = µ_error_reporter;

// สร้าง MicroInterpreter
const tflite::Model* model = tflite::GetModel(g_sin_model_data);
static tflite::MicroInterpreter static_interpreter(
    model,
    micro_op_resolver,
    tensor_arena,
    kTensorArenaSize,
    error_reporter
);
TfLiteTensor* input = static_interpreter.input(0);
TfLiteTensor* output = static_interpreter.output(0);

void setup() {
    Serial.begin(115200);
    while (!Serial);
    
    Serial.println("TinyML on ESP32-S3 - Sin Prediction Model");
    
    // ตั้งค่า input tensor
    input->data.f[0] = 0.0;  // ค่า x เริ่มต้น
    
    // ทำการอนุญาตให้โมเดลทำงาน
    if (static_interpreter.AllocateTensors() != kTfLiteOk) {
        Serial.println("Error allocating tensors!");
        return;
    }
}

void loop() {
    // ทดลองค่าต่างๆ ของ x (0 ถึง 2π)
    for (float x = 0; x <= 6.28; x += 0.1) {
        // ตั้งค่า input
        input->data.f[0] = x;
        
        // รันโมเดล
        if (static_interpreter.Invoke() != kTfLiteOk) {
            Serial.println("Error invoking model!");
            return;
        }
        
        // อ่านผลลัพธ์
        float y_pred = output->data.f[0];
        float y_actual = sin(x);
        
        // แสดงผล
        Serial.printf("x: %.2f, Predicted: %.3f, Actual: %.3f, Error: %.3f\n",
                     x, y_pred, y_actual, abs(y_pred - y_actual));
        
        delay(100);
    }
    
    Serial.println("\n--- Test Complete ---\n");
    delay(5000);
}

💡 เคล็ดลับ: โค้ดนี้เป็นตัวอย่างพื้นฐาน ในการใช้งานจริง คุณจะต้อง:
1. ฝึกโมเดลด้วย Python (TensorFlow/Keras)
2. แปลงเป็น TensorFlow Lite (.tflite)
3. แปลงเป็น C array ด้วย xxd
4. นำไฟล์ .h มารวมในโปรเจกต์

การฝึกโมเดลด้วย Python

# train_sin_model.py
import tensorflow as tf
import numpy as np

# สร้างข้อมูลฝึก
X_train = np.linspace(0, 2*np.pi, 100).reshape(-1, 1).astype(np.float32)
y_train = np.sin(X_train).astype(np.float32)

# สร้างโมเดล Neural Network
model = tf.keras.Sequential([
    tf.keras.layers.Dense(16, activation='relu', input_shape=(1,)),
    tf.keras.layers.Dense(16, activation='relu'),
    tf.keras.layers.Dense(1)
])

model.compile(optimizer='adam', loss='mse')

# ฝึกโมเดล
model.fit(X_train, y_train, epochs=100, verbose=0)

# แปลงเป็น TensorFlow Lite
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
tflite_model = converter.convert()

# บันทึกไฟล์
with open('sin_model.tflite', 'wb') as f:
    f.write(tflite_model)

# แปลงเป็น C array
# xxd -i sin_model.tflite > sin_model_data.h
print("Model trained and saved!")

การปรับปรุงประสิทธิภาพโมเดล

เทคนิคการ Optimize

  • Quantization: แปลงจาก float32 เป็น int8 ลดขนาดโมเดล 75%
  • Pruning: ตัดส่วนที่ไม่สำคัญออก ลดขนาดโมเดล 50%
  • Model Compression: ใช้โครงสร้างโมเดลที่เล็กกว่า
  • Operator Fusion: รวม operations หลายตัวเป็นหนึ่ง

ตัวอย่างการ Quantize

# การ Quantize โมเดล
def representative_dataset():
    for _ in range(100):
        data = np.random.rand(1, 1).astype(np.float32)
        yield [data]

converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.representative_dataset = representative_dataset
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.int8
converter.inference_output_type = tf.int8

quantized_model = converter.convert()

✅ ผลลัพธ์: โมเดลที่ Quantize แล้วมักจะมีขนาดเล็กลง 4 เท่า และทำงานเร็วขึ้น 2-3 เท่า โดยที่ความแม่นยำลดลงเพียงเล็กน้อย

การแก้ปัญหาที่พบบ่อย

❌ ปัญหา: "Allocator failed to allocate"

สาเหตุ: โมเดลใหญ่เกินไป หน่วยความจำไม่พอ

วิธีแก้: เพิ่มขนาด tensor arena หรือทำ quantization โมเดล

❌ ปัญหา: "Did not find op for builtin opcode"

สาเหตุ: โมเดลใช้ operation ที่ไม่รองรับ

วิธีแก้: ตรวจสอบ MicroOpResolver และเพิ่ม ops ที่ต้องการ

❌ ปัญหา: โมเดลทำนายผิดพลาดมาก

สาเหตุ: ข้อมูลไม่ครบ หรือโมเดลเล็กเกินไป

วิธีแก้: เพิ่มข้อมูลฝึก หรือขยายโครงสร้างโมเดล

🎉 สรุป

ในบทความนี้คุณได้เรียนรู้:

  • ✅ แนวคิดพื้นฐานของ TinyML
  • ✅ การติดตั้งซอฟต์แวร์ที่จำเป็น
  • ✅ การสร้างและรันโมเดล Machine Learning บน ESP32-S3
  • ✅ เทคนิคการปรับปรุงประสิทธิภาพโมเดล
  • ✅ การแก้ปัญหาที่พบบ่อย

🚀 ถัดไป: ลองสร้างโปรเจกต์จริง เช่น:

  • 🎤 Voice Recognition ด้วย ESP32-S3
  • 📸 Image Classification ด้วย Camera
  • 🎵 Audio Classification เช่น จดจำเสียง

© 2026 CynoIoT Platform. All rights reserved.

IoT Platform สำหรับคนไทย