Arduino - control statements. Arduino loops Arduino while exit loop

Today we will study an equally important part of the programming language as loops. What are they needed for. Let's set a goal for ourselves. You need to light six LEDs in turn with a period of 50 ms, and then turn them off in turn with the same interval. Well, what could be simpler? We write the following code:
void setup() ( pinMode(2, OUTPUT); pinMode(3, OUTPUT); pinMode(4, OUTPUT); pinMode(5, OUTPUT); pinMode(6, OUTPUT); pinMode(7, OUTPUT); ) void loop () ( digitalWrite(2, HIGH); delay(50); digitalWrite(3, HIGH); delay(50); digitalWrite(4, HIGH); delay(50); digitalWrite(5, HIGH); delay(50) ; digitalWrite(6, HIGH); digitalWrite(7, HIGH); digitalWrite(2, LOW); (4, LOW); digitalWrite(5, LOW); digitalWrite(6, LOW); digitalWrite(50); We initialized six digital pins from the second to the seventh as outputs, and in the main program we wrote alternately turning on the LED, a delay, and so on six times. Afterwards the same thing, but each time the LED was turned off. Now we upload it to Arduino and enjoy the work. But still, something is wrong here. If you look closely at the program code, you will notice that there are parts of the code that are repeated throughout the entire program. For example, the repetition of the pause should immediately catch your eye. And when initializing a pin, only its number changes. When you turn it on and off, only the number changes. For such a small program, of course, you can leave it like that, the controller will eat it up and not choke, but if you need to execute repeated code, for example, 1000 times. I think I have enough patience to fill it, but does MK have enough memory? Of course, you can ask, why the hell do we need 1000 identical operations? Well, yes, it’s hard to imagine.) But that’s not the problem, but if we have an array of 1000 cells. This often happens, for example, several sensors write parameters to an array and how do you figure out how to sort out this mess. It would be necessary to somehow parse it according to some parameters. It is for such incidents that cycles were invented. A loop is a piece of code that is executed a certain number of times. One executed part of a program in a loop is called an iteration. The number of iterations can be from 0 to infinity. To perform loops in the programming language, there are as many as three loop options. Believe me, this is enough for any sophisticated coding. Let's look at all this in more detail.
  • while(condition) ()
  • do() while(condition);
  • for(count variable; condition; increase count variable) ()
First cycle while(condition) (). How does he work. After the word while there must be a condition in parentheses. The condition can be anything as long as it is true. As soon as the condition becomes false, the loop will stop running and the program will continue to run from the next line after the loop. Let's use an example.
char i = 0; while(i Actually, what is written here. First we initialize the count variable i and reset it. Next, we go into the loop and start checking the condition in brackets. If the value i is less than 10, then execute the body of the loop. In the body of the loop itself, we simply increase the value of the counting variable by one and check the condition again. In our case, the loop will be executed 10 times. That is, first the meaning i equals zero. Zero is less than ten. Next, we increased the variable by one and compared, one is less than ten, and so on. As soon as the counting variable becomes equal to ten, then we check, is ten less than ten? Of course not, and after checking the cycle will stop working. This is how this cycle works. What should you do if you need to execute the code in the body of the loop just once, even if it does not satisfy the condition? There is another cycle for this called do() while(condition). It works exactly the same as the previous cycle, except for one thing. In this loop, the body of the loop is executed first, and then the test occurs. Let's see what it looks like in code.
char i = 0; do ( i++; ) while((i > 0) & (i Look how interesting it is. First, like last time, we initialize the counting variable to zero, but in the condition we write that i was more than zero and less than ten. That is, the value of the variable must lie in the range from one to nine. If we had written this using the previous loop, it would never have been executed. But we have a magic word do. That is, what will happen. First, in the body of the loop, the value of the counting variable will increase and become one, and this is greater than zero, the condition will become true. Accordingly, the loop will continue to execute until the counting variable equals ten. And finally, the third version of the cycle. How does he work:
char i; for(i = 0; i How it works. First, we initiate the counting variable again, but without a specific value. Next we write the word for, but in parentheses we first write our counting variable and assign it an initial value. Then we check the condition and if it is true, then we execute the body of the loop and increase the value of the counting variable. Essentially this is the same as while()() so which cycle to use is up to you. A few words about some points. For example, if you write while(1);, then the loop will run forever. Or if with for, then it will look like this for(;;);. Be careful. Sometimes when executing a cycle, you just really want to drop everything and exit it, but the condition does not allow it. What should I do? There is another command for this break;. As soon as the MK comes across this command in the body of the loop, it will immediately exit the loop and continue executing the program from the next line after the loop. But what if, during the operation of the loop, a condition arises that does not satisfy the condition or, for example, a moment at which we do not need to continue executing the end of the body of the loop? The team will help us here continue;. As soon as the MK comes across this command, it drops everything and moves on to the next iteration of the loop. I hope I explained everything clearly. Now having received this knowledge, let's rewrite our program, but using loops.
void setup() ( byte i = 2; // Counting variable while(i // If i is less than 8, then execute the body of the loop ( pinMode(i, OUTPUT); // Initialize pins starting from 2 i++; //Increase the counting variable by one) ) void loop() ( byte i = 2; while(i Let's take a closer look. First we initialized the counting variable i and assigned it a value of two. Why two? But because I specifically chose pins from the second to the seventh, in order to make sure that the initial value does not matter at all. It turned out to be some kind of pun) Well, of course, yes. Next we write the loop condition. We need to do six iterations since we have six LEDs. Great, we think two plus six equals eight. Yeah, so we need to check the counting variable until it is less than eight. That's what they wrote while(i . Now our loop will run six times. What do we need to do inside the body of the loop? Nothing complicated, just enter the output initialization function on the output, just substitute a counting variable instead of the output number. What’s the trick. As soon as the MK enters the body loop, before executing the function of initializing the output, let’s look at the arguments being passed. One of them should contain the output number, and we have a counting variable there. What should we do? But the smart MK will look at what the variable is there and proudly pull it out. number. And we have a 2. Well, great, let’s initialize the second output. Then we’ll increase the value of the counting variable by one more and check the condition. Yeah, three is less than eight, let’s do it all again, only the variable now has three. We will initialize the output for the third time, and then increase the counting variable by one. In this way, by going through the loop, we will set up all the outputs we need. Moreover, increasing the counting variable by one is not a strict condition. Nobody bothers you to write something like this: i = ((127*i)/31) & 0xF4; And this will also work if the condition is true after execution. For the loop, it doesn’t matter what happens in the body; it is interested in whether the condition is true or not. That's all. In the next lesson we will look at functions, why they are needed and try to write our own.

Let's look at how the for, while and do while loop operators work in the Arduino IDE, how to correctly use loops in sketches, and what mistakes to avoid. Using simple examples, we will demonstrate how you can stop a loop or move from one loop to another. In order to understand the correctness of writing cycles, first of all, you should study the types and properties of algorithms in robotics.

How loops work in the Arduino IDE

Any loop in C++ and the Arduino programming language is an action that is repeated many or an infinite number of times. Not a single program for the Arduino microcontroller is complete without a loop, for example, a void loop is called in an infinite loop. There are three types of loop operators: for, while and do while - let's look at each operator and look at how they work using examples.

The working principle of for and while can be explained with the following simple examples. The for loop is executed a finite number of times (indicated in the operator condition); it is used when the program, for example, requires the LED to blink several times. The while loop can run endlessly, for example, when the LED on the Arduino blinks until the data from the sensor changes.

Description of the for loop in Arduino with an example

The for construct in Arduino is defined as follows:

for (initialization; condition; change)( )

A for loop is used to repeat specific commands enclosed in curly braces. This cycle is suitable for performing any repetitive actions.
At initialization a variable is created and an initial value is assigned.
IN condition the value of the variable at which the loop will be executed is recorded.
IN change indicates how the variable will change at each step of the loop.

for (byte i=0; i<=5; i++){ digitalWrite (13, HIGH ); delay (500); digitalWrite (13, LOW ); delay (500); }

In the example sketch, a variable with an initial value is set i=0, the condition states that the loop will run until the variable is equal to or greater than five i<=5 . The change states that the variable will be incremented by one at each step of the loop. Finally, the for loop exits when the variable is equal to five, so the LED will blink five times before the loop ends.

The variable step (change) can be anything. If it is necessary to increase a variable by two units at once, then the change in the counter should be written as follows: i=i+2. The for loop can be used inside the void setup procedure, for example, to indicate the operating mode of several pins at once. And also in the void loop procedure, for example, in the program for sequentially switching on LEDs on Arduino.



Description of the Arduino program with for and while loops

Description of the Arduino while loop with example

The while construct in Arduino is defined as follows:

while (condition)( // commands that will be repeated }

The while loop will run continuously and endlessly as long as the condition in parentheses is true. The loop exit will be reached when the variable in the while condition changes, so something must be changing its value. The variable can be changed in the program code inside a loop or when reading values ​​from any sensor, for example, from an ultrasonic rangefinder HC-SR04.

byte i=0; // need to create a variable before the loop while(i<5){ // loop runs as long as i is less than 5 digitalWrite(13, HIGH); delay(500); digitalWrite(13, LOW); delay(500); i++; // change variable }

When using the while function, the variable must be created before the loop begins. In the example sketch, the LED will blink five times before the cycle ends. If you don't change the variable inside the curly braces i++, then the cycle will repeat endlessly. The second way to exit the Arduino Uno's while loop is to read data from the sensor and use an if statement to change the variable.

Another loop that can be used in the Arduino IDE is the postcondition loop. do...while. When using this construction, commands in a loop will be executed at least once, regardless of the condition, since the condition is checked after the loop body is executed. In the following code example, the LED will turn on regardless of the sensor readings and only then check the postcondition.

int water; // create a variable before the loop do ( digitalWrite (13, HIGH ); water = analogRead (AO); ) while (water<5) // check the sensor digitalWrite(13, LOW);

How to break out of a while or for loop

In the event that it is necessary to exit the body of the loop, regardless of the specified conditions, the operator is used break or goto. The break statement allows you to exit the loop and the program will continue executing the following commands. The goto statement allows you not only to exit the loop, but also to continue executing the program from the desired point along the label, for example, you can go to another loop in Arduino.

Loops using statements for And while are one of the most important constructs of the C++ language that underlies Arduino. They are found in absolutely every sketch, even if you don't know it. In this article, we will take a closer look at loops, find out what is the difference between for and while, how you can simplify writing a program with their help, and what mistakes should be avoided.

If you are still a novice programmer and want to understand what a loop is and why it is needed, look at the next section of this article with a detailed description.

The WHILE operator is used in C++ and Arduino to repeat the same commands an arbitrary number of times. Compared to the FOR loop, the WHILE loop looks simpler; it is usually used where we do not need to count the number of iterations in a variable, but simply need to repeat the code until something changes or some event occurs.

WHILE syntax

while(<условие или список условий>)
{
<программный блок, который будет повторяться>
}

Any language construct that returns a Boolean value can be used as conditions. Conditions can be comparison operations, functions, constants, variables. As with any other logical operations in Arduino, any value other than zero will be perceived as true, zero – false.

// An endless loop while(true)( Serial.println("Waiting..."); ) // A loop that runs until the value of the checkSignal() function changes while(!checkSignal())( Serial.println("Waiting..."); )

Note that the while statement can be used without blocking the block with curly braces, in which case the first command encountered after the loop will be repeated. It is highly not recommended to use while without curly braces, because in this case it is very easy to make a mistake. Example:

While(true) Serial.print("Waiting for interruption"); delay(1000);

In this case, the inscription will be displayed in an endless loop without pauses, because the delay(1000) command will not be repeated. You can spend a lot of time catching such errors - it's much easier to use a curly brace.

Example of using a while loop

Most often, while is used to wait for some event. For example, the readiness of the Serial object for work.

Serial.begin(9600); while (!Serial) ( ; // Some Arduino boards require you to wait until the serial port is free)

An example of waiting for a character to arrive from external devices via UART:

While(Serial.available())( int byteInput = Seria.read(); // Some other actions)

In this case, we will read the values ​​​​as long as Serial.available() returns a non-zero value. Once all the data in the buffer runs out, the loop will stop.

FOR loop in Arduino

In the FOR loop, we have the opportunity not only to set boundary conditions, but also to immediately define a variable for the counter and indicate how its values ​​will change at each iteration.

FOR loop syntax

Here the design will be a little more complicated:
for (<начальное значение счетчика>;<условие продолжения выполнения цикла>;<изменение значения счетчика на каждом шаге>){
<список_команд>
}

The simplest example:

For(int i=5;i<10;i++){ // Конструкция «3 в одном» pinMode(i, OUTPUT); }

We immediately created a variable, initialized it, and indicated that at the end of each cycle the counter value should be increased by one. And that's it - now you can use the variable inside the loop.

The variable step may be different. Here are examples:

  • for(int i=0; i<10; i=i+2) // Шаг 2
  • for(int i=0; i<10; i+=2) // Аналогичен предыдущему
  • for(int i=10; i>0; i–) // Go back – from 10 to 1

do while loop

In some cases, we need to organize the loop in such a way that the instructions of the block are executed at least once, and then the check is carried out. For such algorithms, you can use the do while construct. Example:

Do ( Serial.println("Working"); ) while (checkSomething());

This version of the loop does not present any difficulties - we simply moved the block with the conditions down, so all the contents inside the curly braces after the do operator will be executed before the first check.

Continue and break statements

There are situations when you need to urgently interrupt the execution of a loop inside a loop block, without waiting to move on to the condition checking block. To do this you can use the operator break:

While (true) ( ​​if (checkSomething()) ( break; ) )

If we simply want to stop the progress of the current iteration, but not exit the loop, but go to the condition checking block, then we must use the operator continue:

While (true) ( ​​if (checkSomething()) ( continue; ) )

The continue and break statements can be used with all variants of FOR and WHILE loops.

Nested loops in Arduino

Any variants of loops can be easily combined with each other, making nested structures. Variables defined in the block of the “overlying” loop will be available in the inner one. The most common example of this kind of loop is traversing two-dimensional arrays. In the following example, we use a double loop: the first one will iterate through the rows (variable i), the second, nested, will loop through the columns (variable j) of the array, which we defined in the variable arr.

Int arr; void setup() ( for (int i = 0; i< 10; i++) { for (int j = 0; j < 3; j++) { arr[i][j] = i * j; Serial.println(arr[i][j]); } } }

More about cycles

If you've never worked with loops, let's dive a little into the world of theory and figure out what loops are and why we need these mysterious language constructs.

Why do we need a loop?

In fact, the main task of the loop is to repeat the same language constructs several times. This need arises in almost every program, and certainly not a single Arduino sketch can do without a loop - the loop() function is also called in an infinite loop.

Let's look at the following example. You need to supply power simultaneously to 5 LEDs connected to the Arduino board from pins 5 to 9. The most obvious option for this would be to place five instructions in a row:

digitalWrite(5, HIGH);

digitalWrite(6, HIGH);

digitalWrite(7, HIGH);

digitalWrite(8, HIGH);

digitalWrite(9, HIGH);

Let’s ignore for now the issue of the riskiness of such an action, because the simultaneous inclusion of such a number of LEDs creates an increased load on the board’s power circuit. The main thing for us now is that we have created five lines of code, each of which differs from the others by only one digit. This approach has the following disadvantages:

  • With any change, you will have to make changes to many lines simultaneously. For example, if we need to switch the LEDs to pins 2 to 6 or turn off the voltage instead of turning it on, we will have to make 5 changes to the code. What if there are more instructions and changes?
  • Large code with a large number of similar instructions is inconvenient and unpleasant to read. Five identical lines are not very scary. But the habit of dirty code will eventually lead to tens and hundreds of extra pages in the listing, which will make both you and your colleagues despondent.
  • In the process of “copy-pasting” almost identical instructions, you can easily make a mistake, for example, forgetting to change the pin number: digitalWrite(5, HIGH); digitalWrite(5, HIGH);
  • You can easily fail an interview at any normal software company by showing the interviewer this code.

From all of this, we can conclude that reusing the same strings over and over again should almost always be avoided and replaced with loops. Moreover, in many situations it is impossible to do without cycles; nothing can replace them. You cannot change the number of times the code is repeated while the program is running. For example, you need to process each element data array, received from external devices. You will never predict how much data there will be, how many times the processing will be repeated, and therefore you will not be able to insert the required number of instructions at the time of writing the article.

And here cycles come to our aid.

Syntax rules

Loop in Arduino is a special program block that will be called a certain number of times during program execution. Within this block, we describe the commands themselves that will be called and the rules by which the controller will determine how many times they need to be called.

In our example above, we could tell the controller the following:

Repeat the command digitalWrite 5 times

In an ideal world with robot programmers, this would probably be enough, but since we are talking to the computer in C++, we need to translate this phrase into this language:

Repeat the command – you need to use special instructions that tell the controller that something interesting is about to begin with while or for loops

digitalWrite – leave it as it is, but write it once and enclose it in curly braces. What to do with the pin numbers - just below.

5 times – use a counter for this, which will increase with each repetition. At the beginning (or end) of a block, you can compare the value of this counter with a limit value (in this case 5) using a comparison operation.

Let's look at an example of such a "translated" loop command with a while statement:

Int counter = 0; // A variable that will store the counter value // We ask the processor to repeat the construct in the curly braces until the condition in the parentheses returns true. // In our case, counter is our counter, 5 is the limit value, the condition is that the counter value is less than 5. // But we can specify completely different logical operators while (counter< 5) { digitaWrite(5, HIGH); // Будем включать светодиод counter++; // Увеличиваем значение счетчика } // Дойдя до сюда, исполняющий процессор переместится в начало блока и опять займется проверкой условий. Если условия вернут истину, команды в блоке между { и } выполнятся еще раз. Если условие не выполнится - процессор переместится к концу блока и пойдет дальше. Этот цикл больше его не заинтересует.

For those who noticed an error in the given code, we give a five and write the loop block differently:

While(counter< 5) { // Вот теперь мы будем включать разные светодиоды, с 5 (0+5) по 9 (4+5) digitalWrite(counter + 5, HIGH); counter++; }

The same result can be achieved using a FOR loop:

For(int counter =0; counter<5; counter ++){ digitalWrite(counter+5, HIGH); }

As you can see, in this case we immediately place all the necessary operations with the counter into one FOR instruction - this is much more convenient if you need to count the required amount.

You can get detailed information about the rules for using loops in the relevant sections of this article.

Conclusion

In this article, we looked at very important constructs of the Arduino language: FOR and WHILE loops. You can find these operators in almost any more or less complex sketch, because without loops many operations on data would be impossible. There is nothing complicated in the syntax of loops - you can easily get used to them and can actively use them in your projects.

Every programming language has a set of control instructions that allow you to execute the same code over and over again (a loop), select an appropriate piece of code (conditions), and instructions for exiting the current piece of code.

Arduino IDE borrows most of the necessary controls from C/C++. Their syntax is identical to C. Below we will briefly describe their syntax.

if statement

The if statement allows you to execute a specific fragment of a program depending on the result of checking a certain condition. If the condition is met, then the program code will be executed, but if the condition is not met, then the program code will be skipped. The syntax for the if command is as follows:

If(condition) ( instruction1; instruction2; )

The condition can be any comparison of a variable or value returned by a function. The main criterion for an if condition is that the answer must always be either true or false. Examples of conditions for an if statement:

If(a!=2) ( ) if(x<10) { } if(znak==’B’) { }

Inside the brackets that are written inside the condition, you can execute the code.

People who start learning programming often make the mistake of equating the value of a specified variable using a single "=" sign. Such a notation clearly indicates the assignment of a value to a variable, and, therefore, the condition will always be “true”, that is, fulfilled. Testing that a variable is equal to a certain value is always indicated by a double equals sign (==).

You can use the function state as a condition, for example:

If(init()) ( Serial.print("ok"); )

The above example would be executed as follows: In the first step, the init() function is called. This function returns a value that will be interpreted as "true" or "false". Depending on the comparison result, an “ok” text will be sent or nothing will be sent.

If…else statement

An extended if statement is the if….else statement. It ensures that one piece of code is executed when a condition is true (true), and a second piece of code is executed when the condition is not met (false). The syntax of the f if….else statement is as follows:

If (condition) ( // command A ) else ( // command B )

"A" commands will only be executed when the condition is met, "B" command will be executed when the condition is not met. Simultaneous execution of command “A” and “B” is not possible. The following example shows how to use the if...else syntax:

If (init()) ( Serial.print("ok"); ) else ( Serial.print("error"); )

In this way, you can check the correct execution of the function and inform the user about it.

A common practice is to negate the condition. This is due to the fact that a function that was executed correctly returns the value 0, and a function that executed incorrectly for some reason returns a non-zero value.

The explanation for this “complication of life” is simple. If the function is executed correctly, then this is the only information we need. In case of an error, it is sometimes worth understanding what went wrong and why the function was not performed correctly. And here numbers other than zero come to the rescue, i.e. using digital codes we can determine the type of error. For example, 1 - a problem with reading some value, 2 - there is no space in memory or on disk, etc.

The last modified example shows how to call a function that returns zero when executed correctly:

If (!init()) ( Serial.print("ok"); ) else ( Serial.print("error"); )

Switch case statement

The if statement allows you to test only one condition. Sometimes it is necessary to perform one of the actions depending on the returned or read value. The switch multiple choice operator is ideal for this. The syntax of the switch command is shown below:

Switch (var) ( case 1: //instruction for var=1 break; case 2: //instruction for var=2 break; default: //default instruction (if var is different from 1 and 2) )

Depending on the value of the var variable, instructions in specific blocks are executed. The case label indicates the beginning of a block for the specified value. For example, case 1: means that this block will be executed for the value of var equal to one.

Each block must be terminated with a break command. It interrupts further execution of the switch statement. If the break command is skipped, then the instructions will be executed in subsequent blocks before the break command. The default label is optional, just like else in an if statement. The instructions located in the default block are executed only when the value of the var variable does not match any pattern.

It often happens that the same instructions must be executed for one of several values. This can be achieved as follows:

Switch (x) ( case 1: //instruction for x=1 break; case 2: case 3: case 5: //instruction for x=2 or 3 or 4 break; case 4: //instruction for x=4 break ; case 6: // instruction for x=6 break default: // default instruction (if x is different from 1,2,3,4,5,6)

Depending on the value of the variable x, the corresponding block of instructions will be executed. Repeating case 2: case 3: case 5: informs the compiler that if variable x has the value 2 or 3 or 5, then the same piece of code will be executed.

for statement

The for statement is used to execute the same code over and over again. Often it is necessary to execute the same instructions, changing only the value of some variable. A for loop is ideal for this. The command syntax is as follows:

Int i; for(i=0;i<10;i++) { // инструкции для выполнения в цикле }

The first parameter given in a for statement is the initial value of the variable. Another element is checking the condition for continuing the loop. The loop runs as long as the condition is met. The last element is the change in the value of the variable. Most often we increase or decrease its value (as necessary). In this example, the instructions contained in the loop will be executed at i=0...9.

Often a variable used in a loop is declared there:

For(int i=0;i<10;i++) { // инструкции для выполнения в цикле }

A variable that is used to count the subsequent steps of the loop can be used within it to call a function with the appropriate parameters.

For(int i=10;i>0;i—) ( Serial.print(i); // numbers 10,9,8,7,6,5,4,3,2,1 will be sent)

while statement

The for loop is ideal where we want to do a count. In a situation where we need to perform certain actions as a result of some event that is not necessarily predictable (for example, we are waiting for a button to be pressed), then we can use the while statement, which executes the statement block as long as the condition is satisfied. The syntax of the while statement is as follows:

While(condition) ( // block of instructions to execute)

It is important that the status check occurs at the beginning of the cycle. It may happen that the instructions inside the while loop are never executed. It is also possible to create an infinite loop. Let's look at two examples:

Int x=2; while(x>5) ( Serial.print(x); ) —————————————- int y=5; while(y>0) ( Serial.print(y); )

The first block of statements located inside the while will never be executed. The variable x has a value of two and it will not become greater than 5. In the second example we are dealing with an infinite loop. The variable “y” has a value of 5, i.e. greater than zero. There is no change to the variable "y" inside the loop, so the loop will never complete.

This is a common mistake when we forget to change a parameter that causes the loop to terminate. Below are two correct examples of using a while loop:

Int x=0; while(x<10) { //блок инструкций x++; } —————————————- while(true) { if(условие) break; // блок инструкций }

In the first example, we took care of changing the value of the variable that is checked in the condition. As a result, the cycle will eventually end. In the second example, an infinite loop was intentionally created. This loop is equivalent to the loop() function in the Arduino IDE. In addition, a condition check has been introduced inside the loop, after which the loop ends with the break command.

do…while statement

A variation of the while loop is the do...while loop. In addition to the syntax, it differs in the place where the condition is checked. In the case of do...while, the condition is checked after the block of instructions is executed. This means that the block of instructions in the body of the loop will be executed at least once. Below is the syntax of the do...while command:

Do ( // block of instructions ) while(condition)

Everything that is written about the while operator also applies to do...while. Below is an example of using a do...while loop:

Int x=10; do ( // block of instructions x—; ) while(x>0); —————————————- do ( // block of instructions if (condition) break; ) while(true);

break statement

The break statement allows you to exit the loop (do...while, for, while) and exit the switch option. In the following example, consider executing the break command:

For(i=0;i<10;i++) { if(i==5) break; Serial.print(i); }

The loop must be executed for the numbers 0 through 9, but for the number 5 a condition is met that triggers the break statement. This will exit the loop. As a result, only the numbers 0,1,2,3,4 will be sent to the serial port (Serial.print).

Continue operator

The continue operator causes the loop instructions (do...while, for, while) to stop executing for the current value and proceed to the next loop step. The following example shows how the continue statement works:

For(i=0;i<10;i++) { if(i==5) continue; Serial.print(i); }

As is not difficult to notice, the loop will be executed for values ​​from 0 to 9. For value 5, the continue command will be executed, as a result of which the instructions after this command will not be executed. As a result, the numbers 0,1,2,3,4,6,7,8,9 will be sent to the serial port (Serial.print).

return statement

The return statement ends the execution of the called function and returns a value of a specific type. You can specify a number, a symbol, or a variable of a specific type as a command parameter. It is important that the return value matches the type of the declared function. The following example shows how to use the return statement:

Int checkSensor())( if (analogRead(0) > 400) ( // reading the analog input return 1; // For values ​​greater than 400, 1 is returned else( return 0; // for others, 0 is returned) )

As you can see, you can use multiple return statements in one function, but only one of them will always work. It is acceptable to use the return operator without parameters. This allows you to prematurely terminate a function that does not return any value.

Void function_name() ( instruction1; if(x==0) return; instruction2; instruction3; )

In the example above, instruction1 will execute whenever the function is called. The execution of instruction2 and instruction3 depends on the result of the if command. If the condition is true (true), the return command will be executed and the function will exit.

In the case when the condition is not met, the return command is also not executed, but the instructions instruction2 and instruction3 are executed, and after that the function completes its work.

goto statement

For ideological reasons, it is necessary to skip this description... The goto statement is a command that should not be used in normal programming. It causes code complexity and is a bad programming habit. We strongly recommend that you do not use this command in your programs. Since goto is included in the official documentation on the arduino.cc website, here is a brief description of it. goto command syntax:

…. goto metka; // go to the line labeled 'metka' ..... .... …. metka: // label with which the program will continue working...

The command allows you to go to the designated mark, i.e. to a place in the program.