ESPHome 2026.5.1
Loading...
Searching...
No Matches
stepper.cpp
Go to the documentation of this file.
1#include "stepper.h"
2#include "esphome/core/log.h"
3#include "esphome/core/hal.h"
4
5namespace esphome::stepper {
6
7static const char *const TAG = "stepper";
8
10 // delta t since last calculation in seconds
11 float dt = (now - this->last_calculation_) * 1e-6f;
12 this->last_calculation_ = now;
13 if (this->has_reached_target()) {
14 this->current_speed_ = 0.0f;
15 return;
16 }
17
18 int32_t num_steps = abs(int32_t(this->target_position) - int32_t(this->current_position));
19 // (v_0)^2 / 2*a
20 float v_squared = this->current_speed_ * this->current_speed_;
21 auto steps_to_decelerate = static_cast<int32_t>(v_squared / (2 * this->deceleration_));
22 if (num_steps <= steps_to_decelerate) {
23 // need to start decelerating
24 this->current_speed_ -= this->deceleration_ * dt;
25 } else {
26 // we can still accelerate
27 this->current_speed_ += this->acceleration_ * dt;
28 }
29 this->current_speed_ = clamp(this->current_speed_, 0.0f, this->max_speed_);
30}
32 uint32_t now = micros();
33 this->calculate_speed_(now);
34 if (this->current_speed_ == 0.0f)
35 return 0;
36
37 // assumes this method is called in a constant interval
38 uint32_t dt = now - this->last_step_;
39 if (dt >= (1 / this->current_speed_) * 1e6f) {
40 int32_t mag = this->target_position > this->current_position ? 1 : -1;
41 this->last_step_ = now;
42 this->current_position += mag;
43 return mag;
44 }
45
46 return 0;
47}
48
49} // namespace esphome::stepper
void calculate_speed_(uint32_t now)
Definition stepper.cpp:9
uint32_t IRAM_ATTR HOT micros()
Definition hal.cpp:43
static void uint32_t