I'm trying to get a servo to vibrate slightly after it moves to a position. The servo can move from either direction. Use case is a little "bounce" or vibration on a model railroad semaphore signal just after it changes position.
The below function works but I feel it could be better. bouncePeriod will likely be 40. and bounceStep is usually 15.
void bounceRun (int curServo, int curPos, int typeMove)
{
int m = curPos; int f = curPos;
if (typeMove == 1) {
//Move two steps back
delay(bouncePeriod[curServo]);
m = m - bounceStep[curServo];
pwm1.writeMicroseconds(curServo, m);
delay(bouncePeriod[curServo]);
m = m - bounceStep[curServo];
pwm1.writeMicroseconds(curServo, m);
//Move four steps forward
delay(bouncePeriod[curServo]);
m = m + bounceStep[curServo];
pwm1.writeMicroseconds(curServo, m);
delay(bouncePeriod[curServo]);
m = m + bounceStep[curServo];
pwm1.writeMicroseconds(curServo, m);
delay(bouncePeriod[curServo]);
m = m + bounceStep[curServo];
pwm1.writeMicroseconds(curServo, m);
delay(bouncePeriod[curServo]);
m = m + bounceStep[curServo];
pwm1.writeMicroseconds(curServo, m);
//Move three steps back
delay(bouncePeriod[curServo]);
m = m - bounceStep[curServo];
pwm1.writeMicroseconds(curServo, m);
delay(bouncePeriod[curServo]);
m = m - bounceStep[curServo];
pwm1.writeMicroseconds(curServo, m);
delay(bouncePeriod[curServo]);
m = m - bounceStep[curServo];
//Move two steps forward
pwm1.writeMicroseconds(curServo, m);
delay(bouncePeriod[curServo]);
m = m + bounceStep[curServo];
pwm1.writeMicroseconds(curServo, m);
delay(bouncePeriod[curServo]);
m = m + bounceStep[curServo];
pwm1.writeMicroseconds(curServo, m);
}
if (typeMove == 2) {
//Move two step forward
delay(bouncePeriod[curServo]);
m = m + bounceStep[curServo];
pwm1.writeMicroseconds(curServo, m);
delay(bouncePeriod[curServo]);
m = m + bounceStep[curServo];
pwm1.writeMicroseconds(curServo, m);
//Move four steps back
delay(bouncePeriod[curServo]);
m = m - bounceStep[curServo];
pwm1.writeMicroseconds(curServo, m);
delay(bouncePeriod[curServo]);
m = m - bounceStep[curServo];
pwm1.writeMicroseconds(curServo, m);
delay(bouncePeriod[curServo]);
m = m - bounceStep[curServo];
pwm1.writeMicroseconds(curServo, m);
delay(bouncePeriod[curServo]);
m = m - bounceStep[curServo];
pwm1.writeMicroseconds(curServo, m);
//Move three steps forward
delay(bouncePeriod[curServo]);
m = m + bounceStep[curServo];
pwm1.writeMicroseconds(curServo, m);
delay(bouncePeriod[curServo]);
m = m + bounceStep[curServo];
pwm1.writeMicroseconds(curServo, m);
delay(bouncePeriod[curServo]);
m = m + bounceStep[curServo];
//Move two steps back
pwm1.writeMicroseconds(curServo, m);
delay(bouncePeriod[curServo]);
m = m - bounceStep[curServo];
pwm1.writeMicroseconds(curServo, m);
delay(bouncePeriod[curServo]);
m = m - bounceStep[curServo];
pwm1.writeMicroseconds(curServo, m);
}
//Set final position to what is was at start of function and clear bounceNow trigger
bounceNow [curServo] = 0;
pwm1.writeMicroseconds(curServo, f);
}