Servo MOTOR & MQTT
函式庫更換: 建議使用 ESP32Servo.h 函式庫以獲得穩定的訊號。
腳位定義:原程式使用 D1,在 ESP32 中我們直接使用 GPIO 數字。依您要求改為 GPIO 2。
2. Wokwi 硬體連接 (Pinout)
在 Wokwi 模擬器中,添加 Servo 元件並依下表連線:
| Servo 引腳 (顏色) | ESP32 引腳 |
| GND (黑/棕) | GND |
| VCC (紅) | VIN (5V) |
| PWM (橘/黃) | GPIO 2 |
#include <WiFi.h> // ESP32 使用此函式庫
#include <PubSubClient.h>
#include <ESP32Servo.h> // ESP32 建議使用 ESP32Servo 函式庫
// --- 設定區 ---
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "mqtt-dashboard.com";
const char* subscribe_topic = "alex9ufo/ServoMotor";
const int servoPin = 2; // 您指定的 D2 (GPIO 2)
Servo myservo;
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
delay(100);
Serial.print("\nConnecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi connected");
}
// --- MQTT 訊息處理 ---
void callback(char* topic, byte* payload, unsigned int length) {
String message = "";
for (int i = 0; i < length; i++) {
message += (char)payload[i];
}
int angle = message.toInt(); // 將接收到的文字轉為整數數字
Serial.print("收到主題 [");
Serial.print(topic);
Serial.print("] 角度指令: ");
Serial.println(angle);
// 角度安全限制 0~180 度
if (angle >= 0 && angle <= 180) {
myservo.write(angle);
Serial.println("伺服馬達已轉動。");
} else {
Serial.println("錯誤:角度超出範圍 (0-180)。");
}
}
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
String clientId = "ESP32_Servo_" + String(random(0xffff), HEX);
if (client.connect(clientId.c_str())) {
Serial.println("connected");
client.subscribe(subscribe_topic);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
// ESP32 伺服馬達初始化
ESP32PWM::allocateTimer(0);
myservo.setPeriodHertz(50); // 標準 50Hz
myservo.attach(servoPin, 500, 2400); // 綁定 GPIO 2,設定脈衝寬度
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
3. 如何使用 CMD 測試控制?
您可以透過剛安裝好的 Mosquitto 工具發送角度指令給伺服馬達:
發送到 90 度:
DOS
mosquitto_pub -h mqtt-dashboard.com -t "alex9ufo/ServoMotor" -m "90"
發送到 180 度:
DOS
mosquitto_pub -h mqtt-dashboard.com -t "alex9ufo/ServoMotor" -m "180"




沒有留言:
張貼留言