ESPHome
2026.5.1
Loading...
Searching...
No Matches
esphome
components
stepper
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
5
namespace
esphome::stepper
{
6
7
static
const
char
*
const
TAG =
"stepper"
;
8
9
void
Stepper::calculate_speed_
(
uint32_t
now) {
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
}
31
int32_t
Stepper::should_step_
() {
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
esphome::stepper::Stepper::acceleration_
float acceleration_
Definition
stepper.h:32
esphome::stepper::Stepper::has_reached_target
bool has_reached_target()
Definition
stepper.h:23
esphome::stepper::Stepper::target_position
int32_t target_position
Definition
stepper.h:26
esphome::stepper::Stepper::deceleration_
float deceleration_
Definition
stepper.h:33
esphome::stepper::Stepper::last_calculation_
uint32_t last_calculation_
Definition
stepper.h:36
esphome::stepper::Stepper::last_step_
uint32_t last_step_
Definition
stepper.h:37
esphome::stepper::Stepper::should_step_
int32_t should_step_()
Definition
stepper.cpp:31
esphome::stepper::Stepper::current_speed_
float current_speed_
Definition
stepper.h:34
esphome::stepper::Stepper::calculate_speed_
void calculate_speed_(uint32_t now)
Definition
stepper.cpp:9
esphome::stepper::Stepper::current_position
int32_t current_position
Definition
stepper.h:25
esphome::stepper::Stepper::max_speed_
float max_speed_
Definition
stepper.h:35
hal.h
log.h
esphome::stepper
Definition
stepper.cpp:5
esphome::micros
uint32_t IRAM_ATTR HOT micros()
Definition
hal.cpp:43
uint32_t
static void uint32_t
Definition
crash_handler.cpp:141
stepper.h
Generated by
1.12.0