Yes, it is usually always possible to factor out similar code into a function. Factoring out similar functionality helps see the different logical parts of the code, and can further help you reason about what's going on or simplify the logic even more.
Looking at the different sections side-to-side can help see similarities.
Your main differences is less-than comparisons and decrements in one branch, and greater-than comparisons and increments in the other branch, with everything else being the same.
It's possible there's an even simpler solution, but one way to simplify this could be to define a delta value, either positive or negative, that can invert the operations, and then factor the common functionality into a function.
For completeness, you must pass every needed variable as a parameter into a common function.
This might not be necessary if you factor out variables that belong together into a struct/class.
________________________________________
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
void common_function(int delta, int& initial2, int& turns2, int& position2,
ArrayType positionn2, int l, int i, {fill in what I forgot})
{
before_position_2 = initial2;
dxlSetGoalPosition(SERVO_ID[1], initial2);
initial2 += delta;
delayMicroseconds(400);
if (initial2 > before_position_2 || initial2 < before_position_2)
{
if (initial2 == position2 + MX_MAX_POSITION_VALUE)
{
position2 = initial2;
turns2++;
Serial.print("Vueltas 2: ");
Serial.println(turns2);
}
else if (initial2 == position2 - MX_MAX_POSITION_VALUE)
{
position2 = initial2;
turns2--;
Serial.print("Vueltas 2: ");
Serial.println(turns2);
}
}
}
if (positionn2[l][i] < initial2)
{
int delta = 1.0;
while (positionn2[l][i] < initial2)
{
common_function(delta, initial2, turns2, position2, positionn2, int l, int i, ...);
}
}
else if (positionn2[l][i] > initial2)
{
int delta = -1.0;
while (positionn2[l][i] > initial2)
{
common_function(delta, initial2, turns2, position2, positionn2, int l, int i, ...);
}
}
|
________________________________________
However, there is more you can do beyond this.
if (initial2 > before_position_2 || initial2 < before_position_2)
What is the point of this complication? This can be simplified by just saying
if (initial2 != before_position_2)
Note,
1 2 3 4
|
else if (initial2 == before_position_2)
{
turns2 = turns2;
}
|
Is this a typo? This section of code doesn't change anything.
Last note,
if (initial2 == position2 + MX_MAX_POSITION_VALUE)
I hope those are integers you're comparing. If those are floating-point numbers, == is not an accurate way to compare them.
Edit: Last last note,
If you are in C and not C++, you'll need to pass the values you want to change within the function by pointer and not by value. Or use a struct and pass that by pointer.