refactoring codebase
This commit is contained in:
@@ -1,177 +1,30 @@
|
||||
#include <Arduino.h>
|
||||
#include <WiFi.h>
|
||||
#include <PubSubClient.h>
|
||||
|
||||
// WiFi credentials
|
||||
const char* ssid = "Home";
|
||||
const char* password = "88888888qwE";
|
||||
|
||||
// MQTT Server details
|
||||
const char* mqtt_server = "192.168.31.225";
|
||||
const char* mqtt_user = "test";
|
||||
const char* mqtt_password = "1234";
|
||||
|
||||
WiFiClient espClient;
|
||||
PubSubClient client(espClient);
|
||||
|
||||
// Пины для управления TMC2209
|
||||
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;
|
||||
unsigned long step_interval_us = 0; // Интервал между шагами в микросекундах
|
||||
unsigned long last_feedback_time = 0; // Время последней публикации обратной связи
|
||||
unsigned long total_steps = 0; // Общее количество шагов
|
||||
|
||||
void setup_wifi() {
|
||||
delay(10);
|
||||
WiFi.begin(ssid, password);
|
||||
while (WiFi.status() != WL_CONNECTED) {
|
||||
delay(500);
|
||||
Serial.print(".");
|
||||
}
|
||||
Serial.println("\nWiFi Connected");
|
||||
}
|
||||
|
||||
void startMotor() {
|
||||
motor_running = true;
|
||||
Serial.println("Motor started");
|
||||
}
|
||||
|
||||
void stopMotor() {
|
||||
motor_running = false;
|
||||
digitalWrite(STEP_PIN, LOW);
|
||||
Serial.println("Motor stopped");
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Расчет интервала на основе желаемой скорости в 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) {
|
||||
String message;
|
||||
for (int i = 0; i < length; i++) {
|
||||
message += (char)payload[i];
|
||||
}
|
||||
|
||||
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 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;
|
||||
}
|
||||
}
|
||||
#include "config.h"
|
||||
#include "motor.h"
|
||||
#include "mqtt_handler.h"
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
setup_wifi();
|
||||
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(DIR_PIN, HIGH);
|
||||
digitalWrite(STEP_PIN, LOW);
|
||||
Serial.begin(115200);
|
||||
|
||||
// Инициализация мотора (Core 1 context initially)
|
||||
motorInit();
|
||||
|
||||
// Запуск задачи MQTT на Core 0
|
||||
xTaskCreatePinnedToCore(
|
||||
mqttTask,
|
||||
"MQTT_Task",
|
||||
8192,
|
||||
NULL,
|
||||
3,
|
||||
NULL,
|
||||
0 // CORE 0
|
||||
);
|
||||
|
||||
Serial.println("System Initialized. Multi-core ready.");
|
||||
}
|
||||
|
||||
void loop() {
|
||||
if (!client.connected()) {
|
||||
reconnect();
|
||||
}
|
||||
client.loop();
|
||||
|
||||
if (motor_running) {
|
||||
// Генерируем короткий импульс
|
||||
digitalWrite(STEP_PIN, HIGH);
|
||||
delayMicroseconds(step_interval_us);
|
||||
digitalWrite(STEP_PIN, LOW);
|
||||
delayMicroseconds(step_interval_us);
|
||||
|
||||
// Увеличиваем счетчик шагов
|
||||
total_steps++;
|
||||
}
|
||||
|
||||
// Публикуем обратную связь
|
||||
publishFeedback();
|
||||
// Loop выполняется на Core 1
|
||||
motorLoop();
|
||||
vTaskDelay(pdMS_TO_TICKS(5));
|
||||
}
|
||||
Reference in New Issue
Block a user