Loop and Flip
In programming, a very important concept to understand is the loop. Loops allow you to repeat a sequence of instructions until a condition is met. In DroneBlocks the loop command is known as the "repeat" block. We will use this block to reproduce a series of flips and will revisit the box mission to simplify the code.
Some of our favorite blocks are the "flip" blocks! With a simple command you can program Tello to perform a flip in one of four directions. It is an amazing feat to watch, given there is a great deal of processing that goes on internally to perform this acrobatic maneuver. Tello's flight controller handles this with ease.
We are going to code a mission that uses each of the flip blocks and instructs Tello to perform each of the flips five times--a total of 20 flips. Without the capability of a loop, or repeat block, the code would appear similar to Figure 1.
Figure 1: Twenty flips and redundant blocks
As you can see there is a great deal of repetition in this block code. While it will still accomplish the purpose, it would be fairly easy to accidentally place a block out of order. As your programs grow in complexity, loops will be extremely useful and help reduce the possibility of code being executed out of sequence. Figure 2 demonstrates how to use a repeat block to simplify the code.
Figure 2: Four flips repeated five times
Would you not agree this code looks much better? Imagine writing a flip forty times. Instead of dragging another twenty blocks onto the canvas all you need to do is change the 5 to a 10 in the repeat block...Voila!
Review, then launch your mission to see how awesome Tello flips are!
The Box Mission, Refactored
At this point, let us quickly revisit the box mission from the previous lesson and rewrite the block code using loops. In addition to the benefits we discussed above, this will also give us more maintainable code. If we choose to share our code with another user, they will be able to quickly understand what is going on and be able to modify the program for their needs. Figure 3 shows the refactored code.
Figure 3: Refactored box mission with loops
In case you are wondering, to "refactor" code means to restructure it to be more manageable. The refactored box mission will be much easier to maintain as your coding becomes more advanced. For example, if you wanted make the sides of the box longer you would change the distance to "60" one time instead of four. Loops are a very powerful programming concept.
Now that you have an understanding of loops, we are going to use them in conjunction with variables in the next lesson. Variables will enable you to create code that is more dynamic and smarter.