There is a famous idiom "I can walk and chew gum at the same time". But how can we program a robot to be able to "walk and chew gum at the same time"? How we can program the robot to execute several tasks simultaneously?
To access the full video please subscribe to FLLCasts.com
- 04 Jan 2018
So far we have created programs that execute actions one after another. But sometimes we need to perform two actions at the same time.
For example, if we want to program our robot to move along a given field and meanwhile it needs to move a hand with another motor(s). To be more precise let us say that we want our robot to move along a square and move a medium motor 240 degrees forward, then 240 degrees backward.
Each of the above tasks is relatively easy. The following program will make the robot to move in a square:
and the following program will make its hand move back and forth as described:
The problem arises when we want to perform the above two programs simultaneously.
In such cases, we need multiple threads. When computers have some actions to be performed they order them in threads. Each thread is executed by executing each of the tasks within one by one. If you need to perform two groups of actions simultaneously, you just need a new thread, so that each group will run in its own thread.
In EV3 you can create a new thread in two ways - using a new start block or using wires.
The start block
The start block is the first block under the orange(flow control) palette.
Once you have put the start block on the canvas you will have a new thread. Once the program is running a new thread will be invoked for each of the start buttons on the canvas and the corresponding tasks will be executed. So the solution to our problem will look like this:
Though what happens if we need to perform some actions simultaneously from the middle of the program. Let us assume that we have the same task at hand, but before it we need to rotate our robot at 360 degrees. On one hand, if we add it to the thread where the robot moves in a square, the robot will move its hand while doing a full circle. On the other, if we add it to the thread where we operate the hand, the robot will be confused, because we would want him to move in a square and move in circle simultaneously. That is why we use wires in such cases
You can select the Sequence Plug Exit to align block as shown below:
However, if the blocks are aligned and you select it, a gap between the two blocks will appear:
Now, if you put several blocks outside of the main thread
and select again on the Sequence Plug Exit, we could drag a new wire and connect those blocks.
That way we have solved the new task.