ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
m5stack_unit_bldc.cpp
Go to the documentation of this file.
1#include "m5stack_unit_bldc.h"
2
4#include "esphome/core/log.h"
7
9
10ESPHOME_LOG_TAG(TAG, "m5stack_unit_bldc");
11
12#ifdef USE_TEXT_SENSOR
13// Indexed by the REG_MOTOR_STATUS byte; anything past "Error" reads as "Unknown"
14PROGMEM_STRING_TABLE(MotorStatusStrings, "Standby", "Running", "Error", "Unknown");
15#endif
16
17// The device latches a new direction only once the motor has stopped (datasheet note [1] "Change direction"); the
18// RPM readback says when that is, polled at this rate for at most this many polls
19static constexpr uint32_t DIRECTION_CHANGE_POLL_MS = 200;
20static constexpr uint8_t DIRECTION_CHANGE_MAX_POLLS = 25;
21// What was last saved to the unit's flash, keyed by the I2C address
22static constexpr uint32_t SAVE_PREF_HASH = 0x7B1D4C25;
23
26 return this->write_reg_(REG_SET_RPM, value);
27 return this->write_reg_(REG_PWM, static_cast<uint16_t>(value));
28}
29
32 return this->read_reg_(REG_SET_RPM, value);
33 uint16_t duty;
34 if (!this->read_reg_(REG_PWM, &duty))
35 return false;
36 *value = duty;
37 return true;
38}
39
41 if (!this->write_byte(REG_MODE, static_cast<uint8_t>(this->control_mode_))) {
42 this->mark_failed(LOG_STR("Failed to write control mode"));
43 return;
44 }
45 // The unit keeps driving its last command across an ESP reboot, so the cache and the number start from it, and
46 // a running motor only takes the direction through the stop and restore sequence
47 float command;
48 if (!this->read_command_raw_(&command)) {
49 this->mark_failed(LOG_STR("Failed to read the motor command"));
50 return;
51 }
52 this->last_command_ = command;
53 // REG_DIRECTION is readable (datasheet register 0x60, W/R), so a boot that already matches the configured
54 // direction skips the stop-and-restore cycle entirely instead of spinning the motor down for no reason. A
55 // failed read is treated the same as a mismatch, falling back to the unconditional write below.
56 uint8_t current_direction;
57 bool direction_matches = this->read_byte(REG_DIRECTION, &current_direction) &&
58 current_direction == static_cast<uint8_t>(this->initial_direction_);
59 if (!direction_matches &&
60 (command != 0 ? !this->write_direction_raw_(this->initial_direction_)
61 : !this->write_byte(REG_DIRECTION, static_cast<uint8_t>(this->initial_direction_)))) {
62 this->mark_failed(LOG_STR("Failed to write initial direction"));
63 return;
64 }
66#ifdef USE_SELECT
67 PUBLISH_STATE(this->direction_select_, static_cast<size_t>(this->initial_direction_));
68#endif
69#ifdef USE_NUMBER
70 PUBLISH_STATE(this->command_number_, command);
71#endif
72
73 const uint8_t motor_config[2] = {static_cast<uint8_t>(this->motor_model_), this->pole_pairs_};
74 if (!this->write_reg_(REG_MOTOR_CONFIG, motor_config)) {
75 this->mark_failed(LOG_STR("Failed to write motor model/pole pairs"));
76 return;
77 }
78 if (this->has_pid_ && !this->write_reg_(REG_PID, this->pid_)) {
79 this->mark_failed(LOG_STR("Failed to write PID gains"));
80 return;
81 }
82
83 // The unit's flash has limited write cycles and its live registers do not say whether they are persisted, so
84 // a hash of what was last saved is kept on the ESP: each configuration is saved once, and a failed save is
85 // retried at the next boot
86 if (this->save_to_flash_) {
87 uint32_t wanted = fnv1a_hash_extend(FNV1_OFFSET_BASIS, static_cast<uint8_t>(this->motor_model_));
88 wanted = fnv1a_hash_extend(wanted, this->pole_pairs_);
89 if (this->has_pid_) {
90 for (const int32_t gain : this->pid_)
91 wanted = fnv1a_hash_extend(wanted, gain);
92 }
93 this->save_pref_ = global_preferences->make_preference<uint32_t>(SAVE_PREF_HASH ^ this->address_);
94 uint32_t saved = 0;
95 this->save_pref_.load(&saved);
96 if (saved != wanted) {
97 if (this->write_byte(REG_SAVE_TO_FLASH, 1)) {
98 this->save_pref_.save(&wanted);
99 } else {
100 ESP_LOGW(TAG, "Failed to save settings to flash");
101 }
102 }
103 }
104
105 // Without a readback entity there is nothing to poll
106#ifdef USE_SENSOR
107 if (this->rpm_sensor_ != nullptr || this->frequency_sensor_ != nullptr)
108 return;
109#endif
110#ifdef USE_TEXT_SENSOR
111 if (this->status_text_sensor_ != nullptr)
112 return;
113#endif
114 this->stop_poller();
115}
116
118 bool ok = true;
119#ifdef USE_SENSOR
120 float value;
121 if (this->rpm_sensor_ != nullptr) {
122 if (this->read_reg_(REG_READBACK_RPM, &value)) {
123 this->rpm_sensor_->publish_state(value);
124 } else {
125 ok = false;
126 }
127 }
128 if (this->frequency_sensor_ != nullptr) {
129 if (this->read_reg_(REG_READBACK_FREQ, &value)) {
130 this->frequency_sensor_->publish_state(value);
131 } else {
132 ok = false;
133 }
134 }
135#endif
136#ifdef USE_TEXT_SENSOR
137 uint8_t status;
138 if (this->status_text_sensor_ != nullptr) {
139 if (!this->read_byte(REG_MOTOR_STATUS, &status)) {
140 ok = false;
141 } else if (status != this->last_status_) {
142 this->last_status_ = status;
143 this->status_text_sensor_->publish_state(
144 MotorStatusStrings::get_progmem_str(status, MotorStatusStrings::LAST_INDEX));
145 }
146 }
147#endif
148 this->status_comm_result(ok);
149}
150
152 ESP_LOGCONFIG(TAG,
153 "M5Unit-BLDC:\n"
154 " Control mode: %s\n"
155 " Direction: %s\n"
156 " Motor model: %s\n"
157 " Pole pairs: %u",
158 this->control_mode_ == ControlMode::CONTROL_MODE_CLOSED_LOOP ? LOG_STR_LITERAL("closed loop")
159 : LOG_STR_LITERAL("open loop"),
160 this->initial_direction_ == Direction::DIRECTION_BACKWARD ? LOG_STR_LITERAL("backward")
161 : LOG_STR_LITERAL("forward"),
162 this->motor_model_ == MotorModel::MOTOR_MODEL_HIGH_SPEED ? LOG_STR_LITERAL("high speed")
163 : LOG_STR_LITERAL("low speed"),
164 this->pole_pairs_);
165 LOG_I2C_DEVICE(this);
166 LOG_UPDATE_INTERVAL(this);
167}
168
169// Outside a direction change the cache only follows a write the device accepted, so a refused command is not
170// applied later when the direction change restores the command
172 if (this->is_failed())
173 return false;
174 if (!this->direction_change_pending_ && !this->status_comm_result(this->write_command_raw_(value)))
175 return false;
176 this->last_command_ = value;
177 return true;
178}
179
181 if (this->is_failed())
182 return false;
183 // The direction already driven needs no stop-and-restore cycle
184 if (direction == this->current_direction_ && !this->direction_change_pending_)
185 return true;
186 return this->status_comm_result(this->write_direction_raw_(direction));
187}
188
189// The new direction latches only after the motor stops: command zero, wait for the readback to confirm the stop,
190// then restore. A change already pending has stopped the motor, so only the direction byte is replaced.
192 if (!this->write_byte(REG_DIRECTION, static_cast<uint8_t>(direction)))
193 return false;
194 if (!this->direction_change_pending_ && !this->write_command_raw_(0)) {
195 // The new byte would latch at the next stop; put the driven direction back, best effort
196 this->write_byte(REG_DIRECTION, static_cast<uint8_t>(this->current_direction_));
197 return false;
198 }
200 this->direction_change_pending_ = true;
201 this->direction_change_polls_ = 0;
202 this->set_interval(DIRECTION_CHANGE_POLL_ID, DIRECTION_CHANGE_POLL_MS,
203 [this]() { this->finish_direction_change_(); });
204 return true;
205}
206
208 float rpm;
209 const bool stopped = this->read_reg_(REG_READBACK_RPM, &rpm) && rpm == 0;
210 if (!stopped && ++this->direction_change_polls_ < DIRECTION_CHANGE_MAX_POLLS)
211 return;
213 this->direction_change_pending_ = false;
214 if (!stopped) {
215 // Restoring now could start the motor in the old direction, so the output stays off
216 ESP_LOGW(TAG, "Motor still turning after %u ms; output left at zero",
217 static_cast<unsigned>(DIRECTION_CHANGE_POLL_MS * DIRECTION_CHANGE_MAX_POLLS));
218 this->last_command_ = 0;
219#ifdef USE_NUMBER
220 PUBLISH_STATE(this->command_number_, 0);
221#endif
222 return;
223 }
224 if (this->last_command_ != 0)
226}
227
228} // namespace esphome::m5stack_unit_bldc
uint8_t status
Definition bl0942.h:8
void mark_failed()
Mark this component as failed.
bool is_failed() const
Definition component.h:287
bool cancel_interval(const char *name)
Cancel an interval function.
Definition component.cpp:92
bool status_comm_result(bool ok)
Clears the warning when ok, else sets it with message (default "Communication failed"); returns ok.
void set_interval(const char *name, uint32_t interval, std::function< void()> &&f)
Set an interval function with a const char* name.
Definition component.cpp:88
uint8_t address_
store the address of the device on the bus
Definition i2c.h:327
bool write_byte(uint8_t a_register, uint8_t data) const
Definition i2c.h:312
bool read_byte(uint8_t a_register, uint8_t *data)
Definition i2c.h:272
static constexpr uint32_t DIRECTION_CHANGE_POLL_ID
bool write_reg_(uint8_t reg, const T &value)
bool write_command(float value)
Send the PWM duty (open loop) or target RPM (closed loop).
FanDirection direction
Definition fan.h:5
AlsGain501 gain
PROGMEM_STRING_TABLE(MotorStatusStrings, "Standby", "Running", "Error", "Unknown")
ESPHOME_LOG_TAG(TAG, "m5stack_unit_bldc")
constexpr uint32_t fnv1a_hash_extend(uint32_t hash, const char *str)
Extend a FNV-1a hash with additional string data.
Definition helpers.h:995
constexpr uint32_t FNV1_OFFSET_BASIS
FNV-1 32-bit offset basis.
Definition helpers.h:968
uint32_t value
Definition hal.cpp:41
ESPPreferences * global_preferences
static void uint32_t
ESPPreferenceObject make_preference(size_t, uint32_t, bool)
Definition preferences.h:24