ESPHome  2024.12.2
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  default:
55  step_mode_s = "UNKNOWN";
56  break;
57  }
58  ESP_LOGCONFIG(TAG, " Step Mode: %s", step_mode_s);
59 }
60 void ULN2003::write_step_(int32_t step) {
61  int32_t n = this->step_mode_ == ULN2003_STEP_MODE_HALF_STEP ? 8 : 4;
62  auto i = static_cast<uint32_t>((step % n + n) % n);
63  uint8_t res = 0;
64 
65  switch (this->step_mode_) {
67  // AB, BC, CD, DA
68  res |= 1 << i;
69  res |= 1 << ((i + 1) % 4);
70  break;
71  }
73  // A, AB, B, BC, C, CD, D, DA
74  res |= 1 << (i >> 1);
75  res |= 1 << (((i + 1) >> 1) & 0x3);
76  break;
77  }
79  // A, B, C, D
80  res |= 1 << i;
81  break;
82  }
83  }
84 
85  this->pin_a_->digital_write((res >> 0) & 1);
86  this->pin_b_->digital_write((res >> 1) & 1);
87  this->pin_c_->digital_write((res >> 2) & 1);
88  this->pin_d_->digital_write((res >> 3) & 1);
89 }
90 
91 } // namespace uln2003
92 } // 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:670
void dump_config() override
Definition: uln2003.cpp:36
void write_step_(int32_t step)
Definition: uln2003.cpp:60
void stop()
Stop running the loop continuously.
Definition: helpers.cpp:676
void setup() override
Definition: uln2003.cpp:9
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
HighFrequencyLoopRequester high_freq_
Definition: uln2003.h:39