ESPHome  2024.11.0
uln2003.cpp
Go to the documentation of this file.
1 #include "uln2003.h"
2 #include "esphome/core/log.h"
3 
4 namespace esphome {
5 namespace uln2003 {
6 
7 static const char *const TAG = "uln2003.stepper";
8 
9 void ULN2003::setup() {
10  this->pin_a_->setup();
11  this->pin_b_->setup();
12  this->pin_c_->setup();
13  this->pin_d_->setup();
14  this->loop();
15 }
16 void ULN2003::loop() {
17  int dir = this->should_step_();
18  if (dir == 0 && this->has_reached_target()) {
19  this->high_freq_.stop();
20 
21  if (this->sleep_when_done_) {
22  this->pin_a_->digital_write(false);
23  this->pin_b_->digital_write(false);
24  this->pin_c_->digital_write(false);
25  this->pin_d_->digital_write(false);
26  // do not write pos
27  return;
28  }
29  } else {
30  this->high_freq_.start();
31  this->current_uln_pos_ += dir;
32  }
33 
34  this->write_step_(this->current_uln_pos_);
35 }
37  ESP_LOGCONFIG(TAG, "ULN2003:");
38  LOG_PIN(" Pin A: ", this->pin_a_);
39  LOG_PIN(" Pin B: ", this->pin_b_);
40  LOG_PIN(" Pin C: ", this->pin_c_);
41  LOG_PIN(" Pin D: ", this->pin_d_);
42  ESP_LOGCONFIG(TAG, " Sleep when done: %s", YESNO(this->sleep_when_done_));
43  const char *step_mode_s = "";
44  switch (this->step_mode_) {
46  step_mode_s = "FULL STEP";
47  break;
49  step_mode_s = "HALF STEP";
50  break;
52  step_mode_s = "WAVE DRIVE";
53  break;
54  }
55  ESP_LOGCONFIG(TAG, " Step Mode: %s", step_mode_s);
56 }
57 void ULN2003::write_step_(int32_t step) {
58  int32_t n = this->step_mode_ == ULN2003_STEP_MODE_HALF_STEP ? 8 : 4;
59  auto i = static_cast<uint32_t>((step % n + n) % n);
60  uint8_t res = 0;
61 
62  switch (this->step_mode_) {
64  // AB, BC, CD, DA
65  res |= 1 << i;
66  res |= 1 << ((i + 1) % 4);
67  break;
68  }
70  // A, AB, B, BC, C, CD, D, DA
71  res |= 1 << (i >> 1);
72  res |= 1 << (((i + 1) >> 1) & 0x3);
73  break;
74  }
76  // A, B, C, D
77  res |= 1 << i;
78  break;
79  }
80  }
81 
82  this->pin_a_->digital_write((res >> 0) & 1);
83  this->pin_b_->digital_write((res >> 1) & 1);
84  this->pin_c_->digital_write((res >> 2) & 1);
85  this->pin_d_->digital_write((res >> 3) & 1);
86 }
87 
88 } // namespace uln2003
89 } // namespace esphome
virtual void digital_write(bool value)=0
void loop() override
Definition: uln2003.cpp:16
ULN2003StepMode step_mode_
Definition: uln2003.h:38
virtual void setup()=0
void start()
Start running the loop continuously.
Definition: helpers.cpp:653
void dump_config() override
Definition: uln2003.cpp:36
void write_step_(int32_t step)
Definition: uln2003.cpp:57
void stop()
Stop running the loop continuously.
Definition: helpers.cpp:659
void setup() override
Definition: uln2003.cpp:9
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
HighFrequencyLoopRequester high_freq_
Definition: uln2003.h:39