@@ -43,10 +43,38 @@ ServoHardware::ServoHardware(int pin, int min_pulse_width, int max_pulse_width,
43
43
44
44
/* *************************************************************************/
45
45
/* !
46
- @brief Destructor
46
+ @brief Detaches the servo from the pin and frees the pin for
47
+ other uses.
47
48
*/
48
49
/* *************************************************************************/
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
+ }
50
78
51
79
/* *************************************************************************/
52
80
/* !
@@ -66,6 +94,10 @@ bool ServoHardware::ServoAttach() {
66
94
_is_attached = true ;
67
95
}
68
96
#else
97
+ if (_servo == nullptr ) {
98
+ WS_DEBUG_PRINTLN (" [servo] Error: Failed to detach, servo not created!" );
99
+ return false ;
100
+ }
69
101
rc = _servo.attach (_pin, _min_pulse_width, _max_pulse_width);
70
102
#endif
71
103
@@ -87,8 +119,16 @@ bool ServoHardware::ServoAttach() {
87
119
/* *************************************************************************/
88
120
void ServoHardware::ServoWrite (int value) {
89
121
#ifdef ARDUINO_ARCH_ESP32
122
+ if (!_is_attached) {
123
+ WS_DEBUG_PRINTLN (" [servo] Error: Servo not attached!" );
124
+ return ;
125
+ }
90
126
writeMicroseconds (value);
91
127
#else
128
+ if (_servo == nullptr || !_servo->attached ()) {
129
+ WS_DEBUG_PRINTLN (" [servo] Error: Servo not attached!" );
130
+ return ;
131
+ }
92
132
_servo.writeMicroseconds (value);
93
133
#endif
94
134
}
@@ -103,11 +143,6 @@ void ServoHardware::ServoWrite(int value) {
103
143
*/
104
144
/* *************************************************************************/
105
145
void ServoHardware::writeMicroseconds (int value) {
106
- if (!_is_attached) {
107
- WS_DEBUG_PRINTLN (" [servo] Error: Servo not attached!" );
108
- return ;
109
- }
110
-
111
146
// Clamp value to a valid pulse_width range
112
147
if (value < _min_pulse_width)
113
148
value = _min_pulse_width;
0 commit comments