I'm using a Dynamixel servo and an Arduino Uno in a project, and I'm trying to learn the controls for the servo using the built-in examples. I'm including a simple snippet of example code, which has the servo write to one position, pause, then write to another position, all in the main loop:
// Set Goal Position in RAW value
dxl.setGoalPosition(DXL_ID, 0);
delay(500);
// Check if DYNAMIXEL is in motion
while(dxl.readControlTableItem(MOVING, DXL_ID));
// Set Goal Position in angle(degree)
dxl.setGoalPosition(DXL_ID, 179.0, UNIT_DEGREE);
delay(500);
// Check if DYNAMIXEL is in motion
while(dxl.readControlTableItem(MOVING, DXL_ID));
The "while" loop at the end reads the servo feedback to see if it's moving, but I'm confused about how the true/false evaluation affects the code that follows. I'm familiar with the idea that
While "something"{}
will wait until "something" is no longer true, what does "while" mean if there are no brackets?
If it ends in semicolon, the body is empty, that is there is no code being executed or not, all the action is in the test.
The example just keeps asking if the condition is met, doing nothing but asking until the condition goes false, indicating the end of some process that was being watched.
It is also a common mistaken syntax error; here it is just what is wanted. As long as it is moving, do nothing but ask again and again.
a while statement is the keyword while, followed by a parenthesized expression (the condition), followed by a statement (the body of the loop)
a statement can be one of many different types of statement, e.g. an expression statement, or a compound statement, or an if statement, etc.
an expression statement is an optional expression followed by a semicolon
a compound statement is any number of statements surrounded by curly braces
For example:
while (x < 10)
++x;
Here, ++x is an expression, so ++x; is an expression statement, which is a statement, so it fits the pattern of the while loop.
Similarly,
while (x < 10) {
++x;
}
++x is an expression, ++x; is an expression statement, { ++x; } is a compound statement, which is a statement, which again fits the pattern of the while loop.
Finally,
while (f(x) < 10)
;
The ; is an expression statement (the expression part is optional), so it's a valid statement, and it is the (empty) body of the while loop.
This loop does nothing until the condition f(x) < 10 is satisfied (but it does call the function f on each iteration, of course).
Thanks for your help, it makes sense now. The sketch is polling to see if the servo is moving, and if it is, do nothing until the movement query evaluates to false. If I comment out the "while" loop, it will move as indicated for 500 millis, which is supposed to be the delay between each rotation, but instead it becomes the duration of the rotation.
I also get the desired behavior if I add empty curly braces, which makes me wonder if there's ever a situation where the empty curly braces are actually necessary.