#include <Arduino.h>
#include <Stepper.h>
#include <math.h> // M_PI
/***** Аппаратные константы *****/
constexpr long STEPS_PER_REV = 2048; // 28BYJ‑48 + редуктор
constexpr byte PIN_IN1 = 8;
constexpr byte PIN_IN2 = 10;
constexpr byte PIN_IN3 = 9;
constexpr byte PIN_IN4 = 11;
/***** Габариты механики *****/
constexpr float PULLEY_R = 0.02f; // радиус шкива, м
/***** Параметры подъёма (можно менять) *****/
constexpr float HEIGHT_M = 0.50f; // метры
constexpr float LIFT_TIME_S = 10.0f; // секунды
/***** Производные константы (считаются на этапе компиляции) *****/
constexpr float PULLEY_CIRC = 2.0f * M_PI * PULLEY_R; // м/об
constexpr float ROTATIONS_N = HEIGHT_M / PULLEY_CIRC; // об
constexpr long TOTAL_STEPS = lround(ROTATIONS_N * STEPS_PER_REV); // шаги
/* нужные об/мин, чтобы пройти высоту за LIFT_TIME_S */
constexpr float TARGET_RPM = (HEIGHT_M / LIFT_TIME_S) / PULLEY_CIRC * 60.0f;
Stepper motor(STEPS_PER_REV, PIN_IN1, PIN_IN2, PIN_IN3, PIN_IN4);
/*------------------------------------------------------------------*/
void setup()
{
Serial.begin(115200);
motor.setSpeed(TARGET_RPM); // RPM -> библиотека сама считает задержку
Serial.println(F("=== Stepper lift demo ==="));
Serial.print (F("RPM set to: ")); Serial.println(TARGET_RPM);
Serial.print (F("Total steps: ")); Serial.println(TOTAL_STEPS);
motor.step(TOTAL_STEPS); // единоразовый подъём
}
/*------------------------------------------------------------------*/
void loop() { /* пусто */ }
/*------------------------------------------------------------------*/
// Указываем количество шагов на один оборот
const int stepsPerRevolution = 2048; // для 28BYJ-48 с редуктором
// Подключение к выводам драйвера ULN2003
Stepper myStepper(stepsPerRevolution, 8, 10, 9, 11);
// Параметры подъема
float height = 0.5; // высота подъема в метрах
float timeToLift = 10; // время подъема в секундах
float pulleyRadius = 0.02; // радиус шкива в метрах (например, 2 см)
void setup() {
myStepper.setSpeed(15); // скорость в об/мин (можно подбирать)
Serial.begin(9600);
// Вычисляем длину троса
float ropeLength = height;
// Вычисляем, сколько оборотов нужно сделать
float pulleyCircumference = 2 * 3.1416 * pulleyRadius;
float requiredRotations = ropeLength / pulleyCircumference;
// Вычисляем общее количество шагов
int totalSteps = requiredRotations * stepsPerRevolution;
// Вывод в сериал для отладки
Serial.print("Total steps: ");
Serial.println(totalSteps);
// Движение мотора
myStepper.step(totalSteps);
}
void loop() {
// ничего не делаем
}
Как оптимизировать данный код ?