@@ -43,10 +43,38 @@ ServoHardware::ServoHardware(int pin, int min_pulse_width, int max_pulse_width,
4343
4444/* *************************************************************************/
4545/* !
46- @brief Destructor
46+ @brief Detaches the servo from the pin and frees the pin for
47+ other uses.
4748*/
4849/* *************************************************************************/
49- ServoHardware::~ServoHardware () {}
50+ ServoHardware::~ServoHardware () {
51+ #ifdef ARDUINO_ARCH_ESP32
52+ if (!_is_attached) {
53+ WS_DEBUG_PRINTLN (" [servo] Error: Failed to detach, servo not attached!" );
54+ return ;
55+ }
56+ if (!ledcDetach (_pin)) {
57+ WS_DEBUG_PRINTLN (" [servo] Error: Failed to detach servo from pin!" );
58+ return ;
59+ }
60+ _is_attached = false ;
61+ #else
62+ if (_servo == nullptr ) {
63+ WS_DEBUG_PRINTLN (" [servo] Error: Failed to detach, servo not created!" );
64+ return ;
65+ }
66+ if (!_servo->attached ()) {
67+ WS_DEBUG_PRINTLN (" [servo] Error: Failed to detach, servo not attached!" );
68+ return ;
69+ }
70+ _servo->detach ();
71+ delete _servo;
72+ _servo = nullptr ;
73+ #endif
74+
75+ WS_DEBUG_PRINT (" [servo] Servo detached from pin " );
76+ WS_DEBUG_PRINTLN (_pin);
77+ }
5078
5179/* *************************************************************************/
5280/* !
@@ -66,6 +94,10 @@ bool ServoHardware::ServoAttach() {
6694 _is_attached = true ;
6795 }
6896#else
97+ if (_servo == nullptr ) {
98+ WS_DEBUG_PRINTLN (" [servo] Error: Failed to detach, servo not created!" );
99+ return false ;
100+ }
69101 rc = _servo.attach (_pin, _min_pulse_width, _max_pulse_width);
70102#endif
71103
@@ -87,8 +119,16 @@ bool ServoHardware::ServoAttach() {
87119/* *************************************************************************/
88120void ServoHardware::ServoWrite (int value) {
89121#ifdef ARDUINO_ARCH_ESP32
122+ if (!_is_attached) {
123+ WS_DEBUG_PRINTLN (" [servo] Error: Servo not attached!" );
124+ return ;
125+ }
90126 writeMicroseconds (value);
91127#else
128+ if (_servo == nullptr || !_servo->attached ()) {
129+ WS_DEBUG_PRINTLN (" [servo] Error: Servo not attached!" );
130+ return ;
131+ }
92132 _servo.writeMicroseconds (value);
93133#endif
94134}
@@ -103,11 +143,6 @@ void ServoHardware::ServoWrite(int value) {
103143*/
104144/* *************************************************************************/
105145void ServoHardware::writeMicroseconds (int value) {
106- if (!_is_attached) {
107- WS_DEBUG_PRINTLN (" [servo] Error: Servo not attached!" );
108- return ;
109- }
110-
111146 // Clamp value to a valid pulse_width range
112147 if (value < _min_pulse_width)
113148 value = _min_pulse_width;
0 commit comments