@@ -29,7 +29,20 @@ ServoController::ServoController() {
2929 @brief Destructor
3030*/
3131/* *************************************************************************/
32- ServoController::~ServoController () {}
32+ ServoController::~ServoController () {
33+ // De-initialize all servos
34+ for (int i = 0 ; i < _active_servo_pins; i++) {
35+ if (_servo_hardware[i] != nullptr ) {
36+ delete _servo_hardware[i];
37+ _servo_hardware[i] = nullptr ;
38+ }
39+ }
40+
41+ if (_servo_model != nullptr ) {
42+ delete _servo_model;
43+ _servo_model = nullptr ;
44+ }
45+ }
3346
3447/* *************************************************************************/
3548/* !
@@ -45,6 +58,11 @@ bool ServoController::Handle_Servo_Add(pb_istream_t *stream) {
4558 return false ;
4659 }
4760
61+ if (_active_servo_pins >= MAX_SERVOS) {
62+ WS_DEBUG_PRINTLN (" [servo] Error: Maximum number of servos reached!" );
63+ return false ;
64+ }
65+
4866 wippersnapper_servo_ServoAdd *msg_add = _servo_model->GetServoAddMsg ();
4967 uint8_t pin = atoi (msg_add->servo_pin + 1 );
5068 _servo_hardware[_active_servo_pins] = new ServoHardware (
@@ -55,7 +73,7 @@ bool ServoController::Handle_Servo_Add(pb_istream_t *stream) {
5573 did_attach = _servo_hardware[_active_servo_pins]->ServoAttach ();
5674
5775 // Write the default minimum to a servo
58- if (! did_attach) {
76+ if (did_attach) {
5977 _servo_hardware[_active_servo_pins]->ServoWrite (MIN_SERVO_PULSE_WIDTH);
6078 WS_DEBUG_PRINT (" [servo] Servo attached to pin: " );
6179 WS_DEBUG_PRINT (msg_add->servo_pin );
@@ -91,7 +109,6 @@ bool ServoController::Handle_Servo_Write(pb_istream_t *stream) {
91109 }
92110 wippersnapper_servo_ServoWrite *msg_write = _servo_model->GetServoWriteMsg ();
93111 uint8_t pin = atoi (msg_write->servo_pin + 1 );
94- // find the pin by using getpin()
95112 int servo_idx = -1 ;
96113 for (int i = 0 ; i < _active_servo_pins; i++) {
97114 if (_servo_hardware[i]->GetPin () == pin) {
@@ -107,7 +124,7 @@ bool ServoController::Handle_Servo_Write(pb_istream_t *stream) {
107124 _servo_hardware[servo_idx]->ServoWrite (msg_write->pulse_width );
108125 WS_DEBUG_PRINT (" [servo] Set Pulse Width: " );
109126 WS_DEBUG_PRINT (msg_write->pulse_width );
110- WS_DEBUG_PRINT (" mS on pin: " );
127+ WS_DEBUG_PRINT (" µs on pin: " );
111128 WS_DEBUG_PRINT (msg_write->servo_pin );
112129 return true ;
113130}
0 commit comments