adding more mqtt topics
This commit is contained in:
@@ -1,4 +1,3 @@
|
||||
// arduino_code/Test/src/main.cpp
|
||||
#include <Arduino.h>
|
||||
#include <WiFi.h>
|
||||
#include <PubSubClient.h>
|
||||
@@ -16,22 +15,29 @@ WiFiClient espClient;
|
||||
PubSubClient client(espClient);
|
||||
|
||||
// Пины для управления TMC2209
|
||||
const int DIR_PIN = 18; // Направление
|
||||
const int STEP_PIN = 19; // Шаг
|
||||
const int EN_PIN = 21; // Включение (опционально)
|
||||
const int DIR_PIN = 18;
|
||||
const int STEP_PIN = 19;
|
||||
const int EN_PIN = 21;
|
||||
int rpm = 200;
|
||||
|
||||
// --- НАСТРОЙКИ ДВИГАТЕЛЯ ---
|
||||
const int STEPS_PER_REVOLUTION = 200; // Стандартный шаг 1.8 градуса
|
||||
const int MICROSTEP_FACTOR = 1; // Настройка перемычек на TMC2209 (1, 2, 4, 8, 16, 32...)
|
||||
// -------------------------++
|
||||
|
||||
// Переменные для управления
|
||||
bool motor_running = false;
|
||||
int step_delay = 1000; // Задержка между шагами (в микросекундах)
|
||||
int steps_per_second = 1000; // Количество шагов в секунду
|
||||
unsigned long step_interval_us = 0; // Интервал между шагами в микросекундах
|
||||
unsigned long last_feedback_time = 0; // Время последней публикации обратной связи
|
||||
unsigned long total_steps = 0; // Общее количество шагов
|
||||
|
||||
void setup_wifi() {
|
||||
delay(10);
|
||||
// Подключение к WiFi
|
||||
WiFi.begin(ssid, password);
|
||||
while (WiFi.status() != WL_CONNECTED) {
|
||||
delay(500);
|
||||
Serial.print(".");
|
||||
}
|
||||
Serial.println("\nWiFi Connected");
|
||||
}
|
||||
|
||||
void startMotor() {
|
||||
@@ -41,54 +47,96 @@ void startMotor() {
|
||||
|
||||
void stopMotor() {
|
||||
motor_running = false;
|
||||
digitalWrite(STEP_PIN, LOW);
|
||||
Serial.println("Motor stopped");
|
||||
}
|
||||
|
||||
void updateStepDelay() {
|
||||
// Рассчитываем задержку между шагами
|
||||
step_delay = 1000000 / steps_per_second;
|
||||
void reconnect() {
|
||||
while (!client.connected()) {
|
||||
if (client.connect("ESP32Client", mqtt_user, mqtt_password)) {
|
||||
client.subscribe("motor/control/command");
|
||||
client.subscribe("motor/control/driver");
|
||||
client.subscribe("motor/control/step_per_sec");
|
||||
client.subscribe("motor/control/rpm");
|
||||
} else {
|
||||
delay(5000);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void setSpeed(int speed) {
|
||||
// Установка скорости в шагах в секунду
|
||||
if (speed > 0) {
|
||||
steps_per_second = speed;
|
||||
updateStepDelay();
|
||||
Serial.print("Speed set to: ");
|
||||
Serial.print(speed);
|
||||
Serial.println(" steps/sec");
|
||||
// Расчет интервала на основе желаемой скорости в RPM
|
||||
void setSpeedRPM(int rpm) {
|
||||
if (rpm <= 0) {
|
||||
stopMotor();
|
||||
return;
|
||||
}
|
||||
|
||||
// Общее количество шагов на один полный оборот вала
|
||||
unsigned long total_steps_per_rev = STEPS_PER_REVOLUTION * MICROSTEP_FACTOR;
|
||||
|
||||
// Сколько шагов нужно сделать в секунду для достижения этого RPM
|
||||
// RPM / 60 = оборотов в секунду. Умножаем на шаги на оборот.
|
||||
unsigned long steps_per_sec = (rpm * total_steps_per_rev) / 60;
|
||||
|
||||
// Интервал в микросекундах (1 000 000 мкс в секунде)
|
||||
if (steps_per_sec > 0) {
|
||||
step_interval_us = 1000000UL / steps_per_sec;
|
||||
|
||||
// Ограничение TMC2209: минимальное время импульса ~1-2 мкс + время восстановления
|
||||
// Не ставьте скорость слишком высокой сразу.
|
||||
if (step_interval_us < 10) step_interval_us = 10;
|
||||
|
||||
motor_running = true;
|
||||
|
||||
Serial.print("Set RPM: ");
|
||||
Serial.print(rpm);
|
||||
Serial.print(" | Steps/sec: ");
|
||||
Serial.print(steps_per_sec);
|
||||
Serial.print(" | Interval: ");
|
||||
Serial.print(step_interval_us);
|
||||
Serial.println(" us");
|
||||
}
|
||||
}
|
||||
|
||||
void callback(char* topic, byte* payload, unsigned int length) {
|
||||
// Обработка команд через MQTT
|
||||
String message;
|
||||
for (int i = 0; i < length; i++) {
|
||||
message += (char)payload[i];
|
||||
}
|
||||
|
||||
if (message == "start") {
|
||||
startMotor();
|
||||
} else if (message == "stop") {
|
||||
stopMotor();
|
||||
} else if (message.startsWith("speed:")) {
|
||||
int speed = message.substring(6).toInt();
|
||||
setSpeed(speed);
|
||||
} else if (message.startsWith("turnoff")) {
|
||||
digitalWrite(EN_PIN, HIGH);
|
||||
} else if (message.startsWith("turnon")) {
|
||||
digitalWrite(EN_PIN, LOW);
|
||||
if (strcmp(topic, "motor/control/command") == 0) {
|
||||
if (message == "start") {
|
||||
startMotor();
|
||||
} else if (message == "stop") {
|
||||
stopMotor();
|
||||
}
|
||||
} else if (strcmp(topic, "motor/control/driver") == 0) {
|
||||
if (message == "turnon") {
|
||||
digitalWrite(EN_PIN, LOW);
|
||||
} else if (message == "turnoff") {
|
||||
digitalWrite(EN_PIN, HIGH);
|
||||
}
|
||||
} else if (strcmp(topic, "motor/control/step_per_sec") == 0) {
|
||||
int sps = message.toInt();
|
||||
if (sps > 0) {
|
||||
step_interval_us = 1000000UL / sps;
|
||||
motor_running = true;
|
||||
}
|
||||
} else if (strcmp(topic, "motor/control/rpm") == 0) {
|
||||
rpm = message.toInt();
|
||||
setSpeedRPM(rpm);
|
||||
}
|
||||
}
|
||||
|
||||
void reconnect() {
|
||||
// Повторное подключение к MQTT
|
||||
while (!client.connected()) {
|
||||
if (client.connect("ESP32Client", mqtt_user, mqtt_password)) {
|
||||
client.subscribe("motor/control");
|
||||
} else {
|
||||
delay(5000);
|
||||
}
|
||||
void publishFeedback() {
|
||||
unsigned long current_time = millis();
|
||||
if (current_time - last_feedback_time >= 500) { // Публикация 2 раз в секунду
|
||||
// Публикуем обратную связь
|
||||
client.publish("motor/feedback/rpm", String(rpm).c_str());
|
||||
client.publish("motor/feedback/step_per_seconds", String(step_interval_us > 0 ? 1000000UL / step_interval_us : 0).c_str());
|
||||
client.publish("motor/feedback/totalsteps", String(total_steps).c_str());
|
||||
|
||||
last_feedback_time = current_time;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,16 +146,13 @@ void setup() {
|
||||
client.setServer(mqtt_server, 1883);
|
||||
client.setCallback(callback);
|
||||
|
||||
// Настройка пинов
|
||||
pinMode(DIR_PIN, OUTPUT);
|
||||
pinMode(STEP_PIN, OUTPUT);
|
||||
pinMode(EN_PIN, OUTPUT);
|
||||
|
||||
// Включаем двигатель
|
||||
digitalWrite(EN_PIN, LOW);
|
||||
|
||||
// Начальное направление (вперед)
|
||||
digitalWrite(EN_PIN, LOW); // Включить драйвер
|
||||
digitalWrite(DIR_PIN, HIGH);
|
||||
digitalWrite(STEP_PIN, LOW);
|
||||
}
|
||||
|
||||
void loop() {
|
||||
@@ -115,15 +160,18 @@ void loop() {
|
||||
reconnect();
|
||||
}
|
||||
client.loop();
|
||||
// Обновляем задержку для правильной скорости
|
||||
updateStepDelay();
|
||||
// Управление двигателем
|
||||
|
||||
if (motor_running) {
|
||||
// Выполняем шаг
|
||||
// Генерируем короткий импульс
|
||||
digitalWrite(STEP_PIN, HIGH);
|
||||
delayMicroseconds(step_delay);
|
||||
delayMicroseconds(step_interval_us);
|
||||
digitalWrite(STEP_PIN, LOW);
|
||||
delayMicroseconds(step_delay);
|
||||
delayMicroseconds(step_interval_us);
|
||||
|
||||
// Увеличиваем счетчик шагов
|
||||
total_steps++;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Публикуем обратную связь
|
||||
publishFeedback();
|
||||
}
|
||||
Reference in New Issue
Block a user