@@ -86,12 +86,12 @@ bool ServoHardware::ServoDetach() {
8686*/
8787/* *************************************************************************/
8888bool ServoHardware::ServoAttach () {
89- uint16_t rc = 255 ;
89+ uint16_t rc;
9090
9191// Attach the servo to the pin
9292#ifdef ARDUINO_ARCH_ESP32
9393 if (!ledcAttach (_pin, _frequency, LEDC_TIMER_WIDTH)) {
94- rc = 255 ;
94+ rc = ERROR_SERVO_ATTACH ;
9595 } else {
9696 WS_DEBUG_PRINTLN (" [servo:hw:L99] Servo attached to pin" );
9797 rc = 1 ;
@@ -105,7 +105,7 @@ bool ServoHardware::ServoAttach() {
105105 rc = _servo->attach (_pin, _min_pulse_width, _max_pulse_width);
106106#endif
107107
108- if (rc == 255 ) {
108+ if (rc == ERROR_SERVO_ATTACH ) {
109109 WS_DEBUG_PRINT (" [servo] Error: Failed to attach servo to pin: " );
110110 WS_DEBUG_PRINTLN (_pin);
111111 return false ;
@@ -122,6 +122,24 @@ bool ServoHardware::ServoAttach() {
122122/* *************************************************************************/
123123uint8_t ServoHardware::GetPin () { return _pin; }
124124
125+ /* *************************************************************************/
126+ /* !
127+ @brief Clamps the pulse width to the min/max range
128+ @param value
129+ The value to clamp
130+ @returns The clamped value
131+ */
132+ /* *************************************************************************/
133+ int ServoHardware::ClampPulseWidth (int value) {
134+ if (value < _min_pulse_width) {
135+ value = _min_pulse_width;
136+ }
137+ if (value > _max_pulse_width) {
138+ value = _max_pulse_width;
139+ }
140+ return value;
141+ }
142+
125143/* *************************************************************************/
126144/* !
127145 @brief Writes a value to the servo pin
@@ -141,11 +159,7 @@ void ServoHardware::ServoWrite(int value) {
141159 WS_DEBUG_PRINTLN (" [servo] Error: Servo not attached!" );
142160 return ;
143161 }
144- // Clamp value to a valid pulse_width range
145- if (value < _min_pulse_width)
146- value = _min_pulse_width;
147- if (value > _max_pulse_width)
148- value = _max_pulse_width;
162+ value = ClampPulseWidth (value);
149163 _servo->writeMicroseconds (value);
150164 WS_DEBUG_PRINT (" [servo] Set Pulse Width: " );
151165 WS_DEBUG_PRINT (value);
@@ -164,11 +178,8 @@ void ServoHardware::ServoWrite(int value) {
164178*/
165179/* *************************************************************************/
166180void ServoHardware::writeMicroseconds (int value) {
167- // Clamp value to a valid pulse_width range
168- if (value < _min_pulse_width)
169- value = _min_pulse_width;
170- if (value > _max_pulse_width)
171- value = _max_pulse_width;
181+ // Clamp the value to the min/max range
182+ value = ClampPulseWidth (value);
172183
173184 // Formula from ESP32Servo library
174185 // https://github.com/madhephaestus/ESP32Servo/blob/master/src/ESP32Servo.cpp
0 commit comments