1- #define USE_PCA9685 0 // set 0 to use Arduino to directly control servos
1+ #define USE_PCA9685 1 // set 0 to use Arduino to directly control servos
22
33#ifndef ARDUINO
44#include " ArduinoMock.h"
@@ -12,7 +12,7 @@ namespace
1212#else
1313#if USE_PCA9685 == 1
1414 #include < Wire.h>
15- #include < PCA9685 .h>
15+ #include < Adafruit_PWMServoDriver .h>
1616#else
1717 #include < Servo.h>
1818#endif
@@ -101,7 +101,8 @@ public:
101101};
102102
103103#if USE_PCA9685 == 1
104- PCA9685 gPwmController ;
104+
105+ Adafruit_PWMServoDriver gPwmController = Adafruit_PWMServoDriver();
105106
106107class PCA9685Servo : public ServoBase
107108{
@@ -111,29 +112,35 @@ public:
111112 void attach (const int pin, const int pwmMin, const int pwmMax)
112113 {
113114 _pin = pin;
114- _servoEval = PCA9685_ServoEvaluator (pwmMin, pwmMax);
115+ _pwmMin = pwmMin;
116+ _pwmMax = pwmMax;
115117 }
116118
117119 // ReSharper disable once CppMemberFunctionMayBeConst
118120 void write (const float angle)
119121 {
120122 const auto cAngle = constrain (angle, float (MinAngle), float (MaxAngle));
121- const auto pwm = _servoEval. pwmForAngle ( cAngle);
122- gPwmController .setChannelPWM (_pin, pwm);
123+ const auto pwm = _pwmMin + (_pwmMax - _pwmMin) * cAngle / ( float (MaxAngle) - float (MinAngle) );
124+ gPwmController .setPWM (_pin, 0 , pwm);
123125 }
124126
125127private:
126128 uint8_t _pin = 0 ;
127- PCA9685_ServoEvaluator _servoEval;
129+ int _pwmMin = 150 ;
130+ int _pwmMax = 600 ;
128131};
132+
129133#else
130134
131135class ArduinoServo : public Servo , public ServoBase
132136{
133137public:
138+ using Servo::attach;
139+
134140 void write (float angle)
135141 {
136- Servo::write (constrain (int (angle), MinAngle, MaxAngle));
142+ const auto cAngle = constrain (int (angle), MinAngle, MaxAngle);
143+ Servo::write (cAngle);
137144 }
138145};
139146
@@ -204,10 +211,8 @@ void setup()
204211 Wire.begin (); // Wire must be started first
205212 Wire.setClock (400000 ); // Supported baud rates are 100kHz, 400kHz, and 1000kHz
206213
207- gPwmController .resetDevices (); // Software resets all PCA9685 devices on Wire line
208-
209- gPwmController .init (21 ); // Address pins A5-A0 set to B010101
210- gPwmController .setPWMFrequency (500 ); // Default is 200Hz, supports 24Hz to 1526Hz
214+ gPwmController .begin ();
215+ gPwmController .setPWMFreq (200 );
211216#endif
212217
213218 // assume servos on pin 3,5,6,9 and potentiometers on analog in 0,1,2,3
@@ -251,6 +256,8 @@ void setup()
251256 while (Serial.available ())
252257 Serial.read ();
253258
259+ delay (10 );
260+
254261 // initiate timer
255262 prevTime = 1e-6f * float (micros ());
256263}
0 commit comments