Bluetooth Classic vs BLE, ESP32 BluetoothSerial, pairing, dan test komunikasi.
ESP32 mendukung 2 jenis Bluetooth: Classic (SPP) dan BLE (Low Energy). Keduanya punya kelebihan masing-masing.
Perbandingan Bluetooth Classic vs BLE โ ESP32 mendukung keduanya!
Gunakan library BluetoothSerial bawaan ESP32 untuk komunikasi Bluetooth Classic.
C++ (Arduino)#include "BluetoothSerial.h"
#include <ArduinoJson.h>
BluetoothSerial SerialBT;
#define LED_PIN 2
void setup() {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
// Inisialisasi Bluetooth
SerialBT.begin("ESP32_IoT"); // Nama device BT
Serial.println("Bluetooth started! Pair dengan 'ESP32_IoT'");
}
void loop() {
// Terima command via Bluetooth
if (SerialBT.available()) {
String input = SerialBT.readStringUntil('\n');
input.trim();
JsonDocument doc;
if (!deserializeJson(doc, input)) {
const char* cmd = doc["command"];
if (strcmp(cmd, "ON") == 0) {
digitalWrite(LED_PIN, HIGH);
SerialBT.println("{\"status\":\"OK\",\"led\":\"ON\"}");
Serial.println("BT: LED ON");
}
else if (strcmp(cmd, "OFF") == 0) {
digitalWrite(LED_PIN, LOW);
SerialBT.println("{\"status\":\"OK\",\"led\":\"OFF\"}");
Serial.println("BT: LED OFF");
}
}
}
// Kirim data sensor periodik
static unsigned long lastSend = 0;
if (millis() - lastSend > 2000) {
lastSend = millis();
JsonDocument doc;
doc["suhu"] = 25.0 + random(0, 50) / 10.0;
doc["cahaya"] = analogRead(34);
doc["led"] = digitalRead(LED_PIN) ? "ON" : "OFF";
String output;
serializeJson(doc, output);
SerialBT.println(output);
}
}
Sebelum bikin Flutter app, test dulu pakai app "Serial Bluetooth Terminal" dari Play Store.
{"command":"ON"} โ LED nyala!{"command":"OFF"} โ LED mati!Test Bluetooth pakai Serial Bluetooth Terminal sebelum coding Flutter
Bluetooth Classic menggunakan SPP (Serial Port Profile) โ seperti komunikasi serial virtual melalui udara.
Flow Bluetooth Classic: Discover โ Pair โ Connect SPP โ Send/Receive Data