ESPHome 2026.12.0-dev
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->setup_check(this->write_byte(REG_MODE, static_cast<uint8_t>(this->control_mode_)),
42 LOG_STR("Failed to write control mode")))
43 return;
44 // The unit keeps driving its last command across an ESP reboot, so the cache and the number start from it, and
45 // a running motor only takes the direction through the stop and restore sequence
46 float command;
47 if (!this->setup_check(this->read_command_raw_(&command), LOG_STR("Failed to read the motor command")))
48 return;
49 this->last_command_ = command;
50 // REG_DIRECTION is readable (datasheet register 0x60, W/R), so a boot that already matches the configured
51 // direction skips the stop-and-restore cycle entirely instead of spinning the motor down for no reason. A
52 // failed read is treated the same as a mismatch, falling back to the unconditional write below.
53 uint8_t current_direction;
54 bool direction_matches = this->read_byte(REG_DIRECTION, &current_direction) &&
55 current_direction == static_cast<uint8_t>(this->initial_direction_);
56 if (!direction_matches &&
57 (command != 0 ? !this->write_direction_raw_(this->initial_direction_)
58 : !this->write_byte(REG_DIRECTION, static_cast<uint8_t>(this->initial_direction_)))) {
59 this->mark_failed(LOG_STR("Failed to write initial direction"));
60 return;
61 }
63#ifdef USE_SELECT
64 PUBLISH_STATE(this->direction_select_, static_cast<size_t>(this->initial_direction_));
65#endif
66#ifdef USE_NUMBER
67 PUBLISH_STATE(this->command_number_, command);
68#endif
69
70 const uint8_t motor_config[2] = {static_cast<uint8_t>(this->motor_model_), this->pole_pairs_};
71 if (!this->setup_check(this->write_reg_(REG_MOTOR_CONFIG, motor_config),
72 LOG_STR("Failed to write motor model/pole pairs")))
73 return;
74 if (this->has_pid_ && !this->write_reg_(REG_PID, this->pid_)) {
75 this->mark_failed(LOG_STR("Failed to write PID gains"));
76 return;
77 }
78
79 // The unit's flash has limited write cycles and its live registers do not say whether they are persisted, so
80 // a hash of what was last saved is kept on the ESP: each configuration is saved once, and a failed save is
81 // retried at the next boot
82 if (this->save_to_flash_) {
83 uint32_t wanted = fnv1a_hash_extend(FNV1_OFFSET_BASIS, static_cast<uint8_t>(this->motor_model_));
84 wanted = fnv1a_hash_extend(wanted, this->pole_pairs_);
85 if (this->has_pid_) {
86 for (const int32_t gain : this->pid_)
87 wanted = fnv1a_hash_extend(wanted, gain);
88 }
89 this->save_pref_ = global_preferences->make_preference<uint32_t>(SAVE_PREF_HASH ^ this->address_);
90 uint32_t saved = 0;
91 this->save_pref_.load(&saved);
92 if (saved != wanted) {
93 if (this->write_byte(REG_SAVE_TO_FLASH, 1)) {
94 this->save_pref_.save(&wanted);
95 } else {
96 ESP_LOGW(TAG, "Failed to save settings to flash");
97 }
98 }
99 }
100
101 // Without a readback entity there is nothing to poll
102#ifdef USE_SENSOR
103 if (this->rpm_sensor_ != nullptr || this->frequency_sensor_ != nullptr)
104 return;
105#endif
106#ifdef USE_TEXT_SENSOR
107 if (this->status_text_sensor_ != nullptr)
108 return;
109#endif
110 this->stop_poller();
111}
112
114 bool ok = true;
115#ifdef USE_SENSOR
116 float value;
117 if (this->rpm_sensor_ != nullptr) {
118 if (this->read_reg_(REG_READBACK_RPM, &value)) {
119 this->rpm_sensor_->publish_state(value);
120 } else {
121 ok = false;
122 }
123 }
124 if (this->frequency_sensor_ != nullptr) {
125 if (this->read_reg_(REG_READBACK_FREQ, &value)) {
126 this->frequency_sensor_->publish_state(value);
127 } else {
128 ok = false;
129 }
130 }
131#endif
132#ifdef USE_TEXT_SENSOR
133 uint8_t status;
134 if (this->status_text_sensor_ != nullptr) {
135 if (!this->read_byte(REG_MOTOR_STATUS, &status)) {
136 ok = false;
137 } else if (status != this->last_status_) {
138 this->last_status_ = status;
139 this->status_text_sensor_->publish_state(MotorStatusStrings::get_progmem_str(status));
140 }
141 }
142#endif
143 this->status_comm_result(ok);
144}
145
147 ESP_LOGCONFIG(TAG,
148 "M5Unit-BLDC:\n"
149 " Control mode: %s\n"
150 " Direction: %s\n"
151 " Motor model: %s\n"
152 " Pole pairs: %u",
153 this->control_mode_ == ControlMode::CONTROL_MODE_CLOSED_LOOP ? LOG_STR_LITERAL("closed loop")
154 : LOG_STR_LITERAL("open loop"),
155 this->initial_direction_ == Direction::DIRECTION_BACKWARD ? LOG_STR_LITERAL("backward")
156 : LOG_STR_LITERAL("forward"),
157 this->motor_model_ == MotorModel::MOTOR_MODEL_HIGH_SPEED ? LOG_STR_LITERAL("high speed")
158 : LOG_STR_LITERAL("low speed"),
159 this->pole_pairs_);
160 LOG_I2C_DEVICE(this);
161 LOG_UPDATE_INTERVAL(this);
162}
163
164// Outside a direction change the cache only follows a write the device accepted, so a refused command is not
165// applied later when the direction change restores the command
167 if (this->is_failed())
168 return false;
169 if (!this->direction_change_pending_ && !this->status_comm_result(this->write_command_raw_(value)))
170 return false;
171 this->last_command_ = value;
172 return true;
173}
174
176 if (this->is_failed())
177 return false;
178 // The direction already driven needs no stop-and-restore cycle
179 if (direction == this->current_direction_ && !this->direction_change_pending_)
180 return true;
181 return this->status_comm_result(this->write_direction_raw_(direction));
182}
183
184// The new direction latches only after the motor stops: command zero, wait for the readback to confirm the stop,
185// then restore. A change already pending has stopped the motor, so only the direction byte is replaced.
187 if (!this->write_byte(REG_DIRECTION, static_cast<uint8_t>(direction)))
188 return false;
189 if (!this->direction_change_pending_ && !this->write_command_raw_(0)) {
190 // The new byte would latch at the next stop; put the driven direction back, best effort
191 this->write_byte(REG_DIRECTION, static_cast<uint8_t>(this->current_direction_));
192 return false;
193 }
195 this->direction_change_pending_ = true;
196 this->direction_change_polls_ = 0;
197 this->set_interval(DIRECTION_CHANGE_POLL_ID, DIRECTION_CHANGE_POLL_MS,
198 [this]() { this->finish_direction_change_(); });
199 return true;
200}
201
203 float rpm;
204 const bool stopped = this->read_reg_(REG_READBACK_RPM, &rpm) && rpm == 0;
205 if (!stopped && ++this->direction_change_polls_ < DIRECTION_CHANGE_MAX_POLLS)
206 return;
208 this->direction_change_pending_ = false;
209 if (!stopped) {
210 // Restoring now could start the motor in the old direction, so the output stays off
211 ESP_LOGW(TAG, "Motor still turning after %u ms; output left at zero",
212 static_cast<unsigned>(DIRECTION_CHANGE_POLL_MS * DIRECTION_CHANGE_MAX_POLLS));
213 this->last_command_ = 0;
214#ifdef USE_NUMBER
215 PUBLISH_STATE(this->command_number_, 0);
216#endif
217 return;
218 }
219 if (this->last_command_ != 0)
221}
222
223} // 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.
bool ESPHOME_ALWAYS_INLINE setup_check(bool ok)
Marks the component failed with message (default "Communication failed") unless ok; returns ok.
Definition component.h:235
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:340
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:1141
constexpr uint32_t FNV1_OFFSET_BASIS
FNV-1 32-bit offset basis.
Definition helpers.h:1114
uint32_t value
Definition hal.cpp:59
ESPPreferences * global_preferences
static void uint32_t
ESPPreferenceObject make_preference(size_t, uint32_t, bool)
Definition preferences.h:24