#include <BluetoothSerial.h>
#include <Adafruit_NeoPixel.h>
BluetoothSerial SerialBT;
// ===== WS2812 設定 =====
#define LED_PIN 5
#define LED_COUNT 16
Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);
// ===== 狀態變數 =====
bool isConnected = false;
char cmd = '0';
// ===== 開機指示-副程式 =====
void bootBlueBlink() {
for (int i = 0; i < 3; i++) {
strip.fill(strip.Color(0, 0, 255));
strip.show();
delay(200);
strip.clear();
strip.show();
delay(200);
}
}
// ===== 跑馬燈-副程式 =====
void marquee() {
static int pos = 0;
strip.clear();
strip.setPixelColor(pos, strip.Color(0, 0, 255));
strip.show();
pos = (pos + 1) % LED_COUNT;
delay(100);
}
// ===== 閃紅燈-副程式 =====
void blinkRed() {
strip.fill(strip.Color(255, 0, 0));
strip.show();
delay(300);
strip.clear();
strip.show();
delay(300);
}
// ===== 七彩變色-副程式 =====
void rainbow() {
static int j = 0;
for (int i = 0; i < LED_COUNT; i++) {
strip.setPixelColor(i,
strip.gamma32(strip.ColorHSV((i * 65536 / LED_COUNT + j) % 65536))
);
}
strip.show();
j += 256;
delay(50);
}
/* =========================
⭐ 學生練習區
========================= */
// ===== SETUP =====
void setup() {
Serial.begin(115200);
// SerialBT.begin("連線的藍牙名稱"); // ⭐ 實機用(請取消註解)
strip.begin();
strip.show();
bootBlueBlink();
Serial.println("Bluetooth Ready");
Serial.println("請輸入指令:a / b / c / d");
}
// ===== LOOP =====
void loop() {
/* =========================
🔵【Wokwi 模擬區(用 Serial)】
========================= */
isConnected = true; // ⭐ 模擬「已連線」
// ⭐ 用序列埠輸入指令(取代藍牙)
if (Serial.available()) {
cmd = Serial.read();
Serial.print("收到指令:");
Serial.println(cmd);
}
/* =========================
🔵【實機藍牙用(請取消註解)】
========================= */
/*
isConnected = SerialBT.hasClient();
if (SerialBT.available()) {
cmd = SerialBT.read();
Serial.println(cmd);
}
*/
// 🔴 未連線 → 閃紅燈
if (!isConnected) {
blinkRed();
return;
}
// 🟢 無指令 → 跑馬燈
if (cmd == '0') {
marquee();
}
// 🔵 指令控制
switch (cmd) {
case 'a':
rainbow();
break;
/* =========================
⭐ 學生擴充區
========================= */
// case 'b':
// alternateFlash();
// break;
// case 'c':
// randomColor();
// break;
// case 'd':
// off();
// break;
}
delay(1); // ⭐ 防止ESP32重開機
}