Skip to content

Commit b707ac5

Browse files
committed
esp32: add support for esp-idf v5.x
1 parent b072f36 commit b707ac5

File tree

2 files changed

+31
-11
lines changed

2 files changed

+31
-11
lines changed

src/esp32/Servo.cpp

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -34,26 +34,42 @@
3434

3535
class ServoImpl {
3636
uint8_t pin;
37+
uint8_t channel;
3738

3839
public:
39-
ServoImpl(const uint8_t _pin, const uint8_t _channel) : pin(_pin) {
40-
// Setup timer
40+
ServoImpl(const uint8_t _pin, const uint8_t _channel) : pin(_pin), channel(_channel) {
41+
#if ESP_IDF_VERSION_MAJOR < 5
4142
ledcSetup(_channel, (1000000 / REFRESH_INTERVAL), LEDC_MAX_BIT_WIDTH);
42-
43-
// Attach timer to a LED pin
4443
ledcAttachPin(pin, _channel);
44+
#else
45+
ledcAttachChannel(pin, (1000000 / REFRESH_INTERVAL), LEDC_MAX_BIT_WIDTH, channel);
46+
#endif
4547
}
4648

4749
~ServoImpl() {
50+
#if ESP_IDF_VERSION_MAJOR < 5
4851
ledcDetachPin(pin);
52+
#else
53+
ledcDetach(pin);
54+
#endif
4955
}
5056

51-
void set(const uint8_t _channel, const uint32_t duration_us) {
52-
ledcWrite(_channel, LEDC_US_TO_TICKS(duration_us));
57+
void set(const uint32_t duration_us) {
58+
ledcWrite(ref(), LEDC_US_TO_TICKS(duration_us));
5359
}
5460

55-
uint32_t get(const uint8_t _channel) const {
56-
return LEDC_TICKS_TO_US(ledcRead(_channel));
61+
uint32_t get() const {
62+
return LEDC_TICKS_TO_US(ledcRead(ref()));
63+
}
64+
65+
private:
66+
// read/write channel argument changed to pin between 4.x and 5.x
67+
uint8_t ref() const {
68+
#if ESP_IDF_VERSION_MAJOR < 5
69+
return channel;
70+
#else
71+
return pin;
72+
#endif
5773
}
5874
};
5975

@@ -121,7 +137,7 @@ void Servo::writeMicroseconds(int value)
121137
else if (value > SERVO_MAX())
122138
value = SERVO_MAX();
123139

124-
servos[this->servoIndex]->set(this->servoIndex, value);
140+
servos[this->servoIndex]->set(value);
125141
}
126142
}
127143

@@ -135,7 +151,7 @@ int Servo::readMicroseconds()
135151
if (!servos[this->servoIndex]) {
136152
return 0;
137153
}
138-
return servos[this->servoIndex]->get(this->servoIndex);
154+
return servos[this->servoIndex]->get();
139155
}
140156

141157
bool Servo::attached()

src/esp32/ServoTimers.h

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
#define MAX_PWM_SERVOS 16
22

3+
#if ESP_IDF_VERSION_MAJOR < 5
34
#define LEDC_MAX_BIT_WIDTH SOC_LEDC_TIMER_BIT_WIDE_NUM
5+
#else
6+
#define LEDC_MAX_BIT_WIDTH SOC_LEDC_TIMER_BIT_WIDTH
7+
#endif
48

59
constexpr uint32_t BIT_RESOLUTION = (1 << LEDC_MAX_BIT_WIDTH) - 1;
610

711
#define LEDC_US_TO_TICKS(us) static_cast<uint32_t>((us * BIT_RESOLUTION) / REFRESH_INTERVAL)
8-
#define LEDC_TICKS_TO_US(ticks) static_cast<uint32_t>((ticks * REFRESH_INTERVAL) / BIT_RESOLUTION)
12+
#define LEDC_TICKS_TO_US(ticks) static_cast<uint32_t>((ticks * REFRESH_INTERVAL) / BIT_RESOLUTION)

0 commit comments

Comments
 (0)