Slider doesn't work on Servo - Help

Try this code:

#include <HCPCA9685.h>
#include <Wire.h>
#define I2CAdd 0x40

HCPCA9685 HCPCA9685(I2CAdd);
String state = "";

int servo5Pos;
int servo5PPos;

void setup() {
Wire.begin();
Serial.begin(4800);
HCPCA9685.Init(SERVO_MODE);
HCPCA9685.Sleep(false);
servo5PPos = 63;

}

void loop(){
if (Serial.available() > 0){
state = Serial.readStringUntil('\n'); // Read the data as string
Serial.print(state + "\n");
// If slider has changed value - Move Servo 5 to position
if (state.startsWith("s5")){
String stateS = state.substring(2, state.length()); // Extract only the number. E.g. from "s1120" to "120"
servo5Pos = stateS.toInt(); // Convert the string into integer
// We use for loops so we can control the speed of the servo
// If previous position is bigger then current position
Serial.print(servo5Pos);
if (servo5PPos > servo5Pos){
for (int pos = servo5PPos; pos >= servo5Pos; pos--) {
HCPCA9685.Servo(5, pos);
delay(20);
}
}
if (servo5PPos < servo5Pos){
for (int pos = servo5PPos; pos <= servo5Pos; pos++) {
HCPCA9685.Servo(5, pos);
delay(20);
}
}
servo5PPos = servo5Pos;
}
}
}

And for your message in blocks, append \n at the end

1 Like