the Internet Windows Android

Arduino functions directory. Arduino - Managing Operators

This simulator works best in Chrome browser
Let's look at Arduino on carefully.

Arduino is ne. big computerTo which external chains can be connected. ATMEGA 328P Used in Arduino Uno
This is the largest chip on the board. This chip performs programs that are stored in its memory. You can download the program via USB with using Arduino. IDE. USB port Also provides ARDUINO power.

There is a separate power connector. On the board there are two outputs designated 5V and 3.3V, which are needed in order to power various devices. Also you will find contacts marked as GND, these are the conclusions of the Earth (the Earth is 0B). Arduino Platform, also has 14 digital conclusions (pins) marked with numbers from 0 to 13, which are connected to external nodes and have two states high or low (on or off). These contacts can work as outputs or as inputs, i.e. They can either transfer some data and manage external devices, or receive data from devices. The following conclusions on the board are indicated A0-A5. These are analog inputs that can receive data from different sensors. This is especially convenient when you need to measure a certain range, such as temperature. Analog inputs have additional functionswhich can be used separately.

How to use male fee.

The cabinet is needed to temporarily connect the items, check how the device works, before you sappier all together.
All the following examples are assembled on the batch, so that you can quickly make changes to the diagram and reuse the parts without freezing with the soldering.

There are rows of holes in the dump truck in which you can insert parts and wires. Some of these holes are electrically connected to each other.

The two upper and lower rows are connected by in a row along the entire board. These ranks are used to feed power on the scheme. It can be 5V or 3.3V, but in any case, the first thing you need to do is connect 5V and GND on the dump card, as shown in the figure. Sometimes these row connections can be interrupted in the middle of the board, then if you need, you can connect them, as shown in the picture.








The remaining holes located in the middle of the board are grouped by five holes. They are used to connect the details of the scheme.


The first thing we connect to our microcontroller is a LED. The circuit of electrical connections is shown in the picture.

Why do you need a resistor in the scheme? In this case, it limits the current that passes through the LED. Each LED is designed for a certain current, and if this current is greater, the LED will fail. To find out what nominal value should be a resistor with the help of the Ohm law. For those who do not know or forgot, the law Ohm says that there is a linear dependence of the current from the voltage. Those, the more we make tension to the resistor, the more current flows through it.
V \u003d I * R
Where V.- Difference on resistor
I.- Current via resistor
R.- Resistance to find.
First, we must learn the voltage to the resistor. Most LEDs are 3mm or 5mm, which you will use, have a working voltage 3B. It means that we need to pay off on the resistor 5-3 \u003d 2B.

Then we calculate the current passing through the resistor.
Most 3 and 5mm LEDs are glowing full brightness at a current of 20mA. The current more than this may be outrethged, and the current lower strength will reduce their brightness without causing any harm.

So, we want to turn on the LED into the 5V chain so that there is a current of 20mA. Since all parts are included in one chain on the resistor will also be a current of 20mA.
We get
2B \u003d 20 mA * R
2B \u003d 0.02A * R
R \u003d 100 ohm

100 ohms This is the minimum resistance, it is better to use a little more, because the LEDs have some variation of characteristics.
IN this example Used resistor 220 ohms. Just because the author has a lot of them: Wink :.

Insert the LED into the openings in the middle of the board in such a way that its long output is connected to one of the conclusions of the resistor. The second end of the resistor is connected from 5V, and the second LED output is connected with GND. The LED should light up.

Please note that there is a difference in how to connect the LED. The current flows from a longer output to a shorter. In the diagram, this can be represented that the current flows to the other side where the triangle is directed. Try turning the LED and you will see that it will not shine.

But how you will connect the resistor, there is no difference at all. You can turn it over or try to connect to another output of the LED, it will not affect the operation of the scheme. He will still limit the current through the LED.

Anatomy Arduino Sketch.

Programs for Arduino call Sketch. They consist of two basic functions. Function setup. and function Loop.
Inside this feature you will specify all the basic settings. What conclusions will work on input or output which libraries to connect, initialize variables. Function Setup () It starts only once during the Sketch when the program starts.
This is the main function that is performed after setup (). In fact, this is the program itself. This feature will be endless until you turn off the power.

Arduino flashes LED



In this example, we connect the LED diagram to one of the Arduino digital conclusions and will turn it on and disable it using the program, as well as you will find out several useful features.

This feature is used in setup () part of the program and serves to initialize the conclusions that you will use as the entrance (INPUT) or out (Output). You will not be able to read or write data from Pina until you install it accordingly in pinmode.. This feature has two arguments: pinnumber- This is the number of Pina, which you will use.

Mode.- Because the PIN will work. On the input (INPUT) or out (Output). To ignite the LED we must file a signal OF Arduino. To do this, we configure PIN to exit.
- This feature is used to set a state. (State) Pina. (Pinnumber). There are two main states (in general 3), one thing High, Pine will be 5V, the other is Low. And on Pinea will be 0V. It means that we need to light the LED on Pinea, connected to the LED to set a high level. High.

Delay. It serves to delay the work of the program to the period specified in the MSEK.
Below is the code that causes the LED flashing.
// LED Blink int ledpin \u003d 7; // PIN ARDUINO to which the Void Setup () LED (LEDPIN, OUTPUT); // Installing Pina Like Output) Void Loop () (DigitalWrite (LEDPIN, HIGH); // LED Delay (1000); // Delay 1000 MSEK (1 sec) DigitalWrite (LEDPIN, LOW); // Turn off the Delay LED (1000); // Wait 1 sec)

Small codes.
Rows that begin with "//" This comments Arduino ignores them.
All commands end with a comma point if you forget them, then get an error message.

ledpin.- This is a variable. Variables are used in programs for storing values. In this example, variable ledpin. Assigns to 7, this is the number of Pina Arduino. When Arduino in the program will meet a string with a variable ledpin. He will use the value that we indicated earlier.
So recording pinmode (Ledpin, Output) Similar entries pinmode (7, Output).
But in the first case, it is enough for you to change the variable and it will change in each row, where it is used, and in the second case you, to change the variable, you will have to make changes in each team.

The first line indicates the type of variable. When programming Arduino, it is important to always declare the type of variables. While you have enough to know that Int. Announces negative and positive numbers.
Below is the simulation of the Sketch. Click Start to view the operation of the scheme.

As expected, the LED goes out and lights up one second. Try to change the delay to see how it works.

Control multiple LEDs.

In this example, you will learn how to manage multiple LEDs. To do this, set another 3 LEDs on the board and connect them to the resistors and the outputs of Arduino, as shown below.

In order to enable and disable LEDs in turns. You need to write a program similar to this:
// MULTI LED BLINK INT LED1PIN \u003d 4; int led2pin \u003d 5; int led3pin \u003d 6; int led4pin \u003d 7; void setup () (// Installing Pins as Pinmode Output (LED1PIN, OUTPUT); Pinmode (LED2PIN, Output); Pinmode (LED3PIN, OUTPUT); Pinmode (LED4PIN, OUTPUT);) Void Loop () (DigitalWrite (LED1PIN, HIGH ); // Welcome LED Delay (1000); // Delay 1 sec DigitalWrite (LED1PIN, LOW); // Excele the Delay LED (1000); // Delay 1 sec // Do the Same for the Other 3 LEDs DigitalWrite (LED2PIN , HIGH); // LED Delay (1000); // Delay 1 sec DigitalWrite (LED2PIN, LOW); // Excele the Delay LED (1000); // Delay 1 sec DigitalWrite (LED3PIN, HIGH); // Slash LED Delay (1000); // Delay 1 sec DigitalWrite (LED3PIN, LOW); // Extend Delay LED (1000); // Delay 1 sec DigitalWrite (LED4PIN, HIGH); // LED DELAY LED (1000); // Delay 1 sec DigitalWrite (LED4PIN, LOW); // Extend Delay LED (1000); // Delay 1 sec)

This program will work perfectly, but this is not the most rational solution. The code must be changed. In order for the program to work since during the time we apply a design called.
Cycles are convenient when you need to repeat the same action several times. In the code held above, we repeat the lines

DigitalWrite (LED4PIN, HIGH); Delay (1000); DigitalWrite (LED4PIN, LOW); Delay (1000);
Full Sketch Code in Attachment (Downloads: 1384)

LED brightness adjustment

Sometimes you need to change the brightness of the LEDs in the program. This can be done using the command. analogWrite () . This command quickly includes and turns off the LED that the eye does not see this flicker. If the LED half of time is turned on, and half turns off, it will seem visually that it glows half of its brightness. This is called pulse modulation (PWM or PWM in English). PWM applies quite often, since it can be controlled by an "analog" component using a digital code. Not all the conclusions of Arduino are suitable for these purposes. Only those conclusions, about which such designation is drawn " ~ ". You will see it next to the outputs of 3,5,6,9,10,11.
Connect one of your LEDs with one of the conclusions of PWM (the author is a conclusion 9). Now run the flashing of the LED, but first change the command digitalWrite () on the analogWrite (). analogWrite () It has two arguments: the first is the output number, and the second value of PWM (0-255), with reference to the LEDs it will be their luminescence brightness, and for electric motors the speed of rotation. Below is an example code for different brightness of the LED.
// Change the brightness of the Int LEDPin \u003d 9; // to this output, the Void Setup (Pinmode (LEDPIN, OUTPUT); // PIN initialization to the output) void loop () (AnalogWrite (LEDPIN, 255); // Full brightness (255/255 \u003d 1) Delay (1000); // Pause 1 sec DigitalWrite (LEDPIN, LOW); // Turn off the Delay LED (1000); // Pause 1 sec AnalogWrite (LEDPIN, 191); // Brightness on 3/4 (191/255 ~ \u003d 0.75) Delay (1000); // pause 1 sec DigitalWrite (LEDPIN, LOW); // Turn off the Delay LED (1000); // Pause 1 sec AnalogWrite (LEDPIN, 127); // Half brightness (127/255 ~ \u003d 0.5) Delay (1000); // Pause 1 sec DigitalWrite (LEDPIN, LOW); // Turn off the Delay LED (1000); // Pause 1 sec AnalogWrite (LEDPIN, 63); // quarter of brightness (63/255 ~ \u003d 0.25) Delay (1000); // pause 1 sec DigitalWrite (LEDPIN, LOW); // Turn off the Delay LED (1000); // pause 1 s)

Try to change the value of PWM in the team analogWrite ()To see how it affects the brightness.
Next, you will learn how to adjust the brightness smoothly from full to zero. You can, of course, copy a piece of code 255 times
AnalogWrite (Ledpin, Brightness); Delay (5); // Short Delay Brightness \u003d Brightness + 1;
But, you yourself understand - it will not be practical. It is best to use the FOR cycle that used earlier.
The following example uses two cycles, one to reduce brightness from 255 to 0
for (int brightness \u003d 0; brightness \u003d 0; brightness -) (AnalogWrite (LEDPIN, BRIGHTNESS); Delay (5);)
delay (5) Used to slow down the growth rate and reduction of brightness 5 * 256 \u003d 1280 ms \u003d 1.28 sec.)
In the first line used " bRIGHTNESS-"In order for the brightness value to decrease by 1, each time the cycle is repeated. Please note that the cycle will work as long as bRIGHTNESS\u003e \u003d 0. By changing the sign > On the sign >= We turned on 0 in the brightness range. This sketch is modeled below. // Smoothly change the brightness int ledpin \u003d 9; // A Void Setup (Pinmode (LEDPIN, OUTPUT); // Pin Initialization) Void Loop () (// Smoothly increase the brightness (0 to 255 ) for (int brightness \u003d 0; brightness \u003d 0; brightness -) (AnalogWrite (Ledpin, Brightness); Delay (5);) Delay (1000); // We are waiting for 1 sec // Smoothly reduce the brightness (255 to 0) For (int brightness \u003d 255; brightness\u003e \u003d 0; brightness -) (AnalogWrite (Ledpin, Brightness); Delay (5);) Delay (1000); // We are waiting for 1 sec))
This is not very good, but the idea is understandable.

RGB LED and Arduino

The RGB LED is actually three LEDs of different color in one case.

Including different LEDs with different brightness, you can combine and get different colors. For Arduino, where the amount of brightness gradations is 256 you will receive 256 ^ 3 \u003d 16581375 possible colors. In fact, they will certainly be less.
LED, which we will be used by a common cathode. Those. All three LEDs are constructively connected by cathodes to one conclusion. We will connect this conclusion to the GND output. The remaining conclusions, through restrictive resistors, must be connected to the PWM conclusions. The author used the conclusions 9-11. In order, it can be controlled by each LED separately. In the first Sketch, it is shown how to enable each LED separately.



// RGB LED - Test // Pin Connections int red \u003d 9; int green \u003d 10; INT BLUE \u003d 11; void setup () (Pinmode (Red, Output); Pinmode (Blue, Output); Pinmode (Green, Output);) void loop () (// Turning on / off the Red LED DigitalWrite (Red, High); Delay (500) ; DigitalWrite (Red, Low); Delay (500); // Turn on / off Green LED DigitalWrite (Green, High); Delay (500); DigitalWrite (Green, Low); Delay (500); // Enable / disable blue DigitalWrite LED (Blue, High); Delay (500); DigitalWrite (Blue, Low); Delay (500);)

The following example uses commands analogWrite () And to get different random brightness values \u200b\u200bfor LEDs. You will see different colors that change randomly.
// RGB LED - Random Colors // Pin Connections int red \u003d 9; int green \u003d 10; INT BLUE \u003d 11; Void Setup () (Pinmode (Red, Output); Pinmode (Blue, Output); Pinmode (Green, Output);) void loop () (// Pick a Random Color Analogwrite (Red, Random (256)); AnalogWrite ( Blue, Random (256)); AnalogWrite (Green, Random (256)); Delay (1000); // Wait One Second)

Random (256)- Returns random number ranging from 0 to 255.
In the attached sketch file, which will demonstrate smooth transitions of colors from red to green, then to blue, red, green, etc. (Downloads: 381)
The sketch example works, but there is a lot of recurring code. You can simplify the code by writing your own auxiliary functionwhich will smoothly change one color to another.
This is how she will look like: (Downloads: 414)
Let's consider defining a function in parts. The function is called fader. And has two arguments. Each argument is separated by a comma and has a type declared in the first row of the function of determining the function: void Fader (Int Color1, Int Color2). You see that both arguments are declared as int., and they are assigned names color1. and color2. As conditional variables to determine the function. Void. means that the function does not return any values, it simply executes commands. If it was necessary to write a function that returned the result of multiplication it would look like this:
INT Multiplier (int Number1, int Number2) (int product \u003d number1 * number2; return product;)
Please note how we declared the type int. As a type of return value instead
void..
Inside the function, the teams that you have already used in the previous Sketch, only the numbers of the conclusions were replaced by color1. and color2.. The function is called fader., its arguments are calculated as color1 \u003d red and color2 \u003d Green.. In the archive full sketch using functions (Downloads: 313)

Button

In the next Sketch, a button will be used with normally open contacts, without fixing.


This means that while the button is not pressed, the current does not go through it, and after releasing, the button returns to its original position.
In the diagram, in addition to the button, a resistor is used. In this case, it does not limit the current, and "pulls up" the button to 0B (GND). Those. While the button is not pressed on the Arduino output, to which it is connected, there will be a low level. The resistor used in the 10 com.


// Determine the press of the Int ButtonPin \u003d 7 button; void setup () (Pinmode (Buttonpin, Input); // Initialize PINs to input Serial.begin (9600); // Initialize the serial port) Void Loop () (if (DigitalRead (ButtonPin) \u003d\u003d High) (// if The button is pressed by serial.printLN ("PRESSED"); // display the inscription "PRESSED") ELSE (serial.println ("unpressed"); // otherwise "unpressed"))
In this sketch, several new teams.
- This command accepts High value (high level) and Low (low), that output that we check. Pre-in setup () This output must be configured to the input.
; // Where Buttonpin is the output number where the button is connected.
The serial port allows you to send Arduino messages to a computer, while the controller itself executes the program. This is useful for debugging the program, sending messages to other devices or applications. To enable data transfer through a serial port (Other name Uart or USart), you must initialize it in Setup ()

Serial.begin () It has only one argument is the data transfer rate between Arduino and a computer.
Sketch uses a command to display a message on the screen in Arduino IDE (Tools \u003e\u003e Serial Monitor).
- The design allows you to control the progress of the program, smoking several checks in one place.
If (if) DigitalRead Returns High, then the word "pressed" is displayed on the monitor. ELSE (otherwise) the word "pressed" is displayed on the monitor. Now you can try to turn on and off the LED by pressing the button.
// Button Press Detection with Led Output int buttonpin \u003d 7; int ledpin \u003d 8; Void Setup () (Pinmode (Buttonpin, Input); // This Time We Will Set Button Pin AS INPUT PINMODE (LEDPIN, OUTPUT); serial.begin (9600);) Void Loop () (if (DigitalRead (ButtonPin) \u003d \u003d High) (DigitalWrite (LEDPIN, HIGH); serial.printLN ("PRESSED");) ELSE (DigitalWrite (LEDPIN, LOW); serial.println ("unpressed");))

Analog input.

analogRead. Allows you to read the data from one of the analog Arduino outputs and displays a value in the range from 0 (0B) to 1023 (5V). If the voltage at analog input is 2.5V, then it will be printed 2.5 / 5 * 1023 \u003d 512
analogRead. It has only one argument is an analog input number (A0-A5). The following Sketch provides a voltage reading code with a potentiometer. To do this, connect an alternating resistor, extreme outputs to Pins 5V and GND, and the average output to the input A0.

Run the following code and look at the Serial Monitor, how the values \u200b\u200bare changing depending on the rotation of the resistor handle.
// ANALOG INPUT INT POTPIN \u003d A0; // To this Pina, the central output of the Void setup () potentiometer is connected to this (// Analog PIN by default is connected to the input, so initialization is not needed by Serial.begin (9600);) void loop () ( INT POTVAL \u003d Analogread (Potpin); // Potval IS A Number Between 0 and 1023 Serial.printLN (Potval);)
The following sketch combines the test of the button and the Skatch control of the brightness of the LED. The LED will turn on from the button, and control the brightness of the glow will be a potentiometer.
// Button Press Detection WITH LED OUTPUT AND VARIABLE INTENSITY INT BUTTONPIN \u003d 7; int ledpin \u003d 9; INT POTPIN \u003d A0; void setup () (Pinmode (Buttonpin, Input); Pinmode (Ledpin, Output); serial.begin (9600);) void loop () (if (DigitalRead (Buttonpin) \u003d\u003d High) (// If Button PRESSED INT ANALOGVAL \u003d Analogread (Potpin); int scaledval \u003d map (Analogval, 0, 1023, 0, 255); AnalogWrite (Ledpin, Scaledval); // Turn on Led with Intensity Set by Pot Serial.printLN ("PressED");) Else (DigitalWrite (LEDPIN, LOW); // Turn Off if Button Is Not Prasedn Serial.printLN ("Unpressed");))

Each programming language has a set of control commands providing multiple execution of the same code (cycle), selecting a suitable code fragment (conditions) and instructions for exiting the current code fragment.

Arduino IDE borrowed from C / C ++ most of the necessary controls. Their syntax is identical with C. Below we in the two words we describe their syntax.

IF operator

The IF operator allows you to perform a specific fragment of the program, depending on the result of the test of a specific condition. If the condition is executed, the program code will be executed if the condition is not executed, the program code will be missed. The syntax of the IF command is as follows:

IF (condition) (instruction1; instruction2;)

The condition may be any comparison of the variable or value returned by the function. The main criterion for the conditions if is that the answer should always be or truth (true) or false (false). Examples of conditions for the IF operator:

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

Inside the brackets that are spelled out within the condition, you can perform code.

People who begin to study programming often make a mistake, equating the value of the specified variable using one sign "\u003d". Such an entry clearly indicates the assignment of the value of the variable, and, therefore, the condition will always be "true", that is, run. Check that the variable is equal to a specific value, always denotes the double sign equal to (\u003d\u003d).

As a condition, you can use the function of the function, for example:

If (init ()) (serial.print ("OK");)

The example above will be performed as follows: In the first step, the init () function is called. This feature returns a value that will be interpreted as "True" or "False". Depending on the result of the comparison, the text "OK" will be sent or nothing will be sent.

IF ... ELSE operator

An extended IF operator is an IF ....else operator. It ensures the execution of one code fragment when the condition is performed (true), and executing the second code fragment if the condition is not performed (FALSE). Syntax operator if ....else looks like this:

IF (condition) (// Team A) ELSE (// Team B)

The "A" commands will be executed only if the condition is executed, the "B" command will be executed when the condition is not executed. The simultaneous execution of the "A" and "B" command is impossible. The following example shows how to use the syntax if ... ELSE:

If (init ()) (serial.print ("OK");) ELSE (serial.print ("error");)

Similarly, you can check the correctness of the function and inform the user.

The usual practice is denial of conditions. This is due to the fact that the function that is executed correctly returns the value of 0, and the function that has worked incorrect for some reason returns a non-zero value.

An explanation of such a "complication of life" is simple. If the function is performed correctly, then this is the only information that we need. In the case of an error, it is sometimes necessary to understand what went wrong why the function is not fulfilled correctly. And here, numbers differ from zero come to the rescue, i.e. using digital codes, we can determine the type of error. For example, 1 is a problem with reading some value, 2 - no place in memory or on a disk, etc.

In the last modified example, it is shown how to call a function that returns zero with proper execution:

If (! Init ()) (serial.print ("OK");) ELSE (serial.print ("Error");)

Operator SWITCH CASE.

The IF statement allows you to check only one condition. Sometimes it is necessary to perform one of the actions depending on the returned or read value. For this, the multiple selection operator is a multiple SWITCH. The Switch command syntax is shown below:

SWITCH (VAR) (Case 1: // instruction for var \u003d 1 break; Case 2: // instruction for var \u003d 2 break; default: // default instruction (if var differs from 1 and 2))

Depending on the value of the VAR variable, instructions are performed in certain blocks. Case label means the start of the block for the specified value. For example, Case 1: Means that this unit will be made for the value of the variable var values \u200b\u200bof one.

Each block must be completed using the Break command. It interrupts the further execution of the SWITCH operator. If the break command is missing, then the instructions will be performed in subsequent blocks to the Break command. Default label is not mandatory, like ELSE in the IF command. The instructions located in the Default block are performed only when the value of the variable var by VAR is not suitable for any template.

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

Switch (x) (Case 1: // Instructions for X \u003d 1 BREAK; CASE 2: CASE 3: CASE 5: // Instructions for x \u003d 2 or 3 or 4 Break; Case 4: // Instructions for X \u003d 4 Break ; Case 6: // Instructions for x \u003d 6 Break; Default: // Default Instructions (if x differs from 1,2,3,4,5,6))

Depending on the value of the variable X, the appropriate instruction unit will be performed. Repetition Case 2: Case 3: Case 5: Informs the compiler that if the variable X has a value of 2 or 3 or 5, then the same code fragment will be performed.

Operator for

The FOR Operator is used to multiple the same code. It is often necessary to complete the same instructions by changing only the value of some variable. For this, the For cycle is perfect. The syntax of the command is as follows:

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

The first parameter cited in the FOR instruction is the initial value of the variable. Another element is to verify the conditions for the continuation of the execution of the cycle. The cycle is performed until the condition is performed. The last element is a change in the value of the variable. Most often, we increase or reduce its value (if necessary). In this example, the instructions contained in the cycle will be performed at i \u003d 0 ... 9.

Often the variable used in the cycle is declared ibid.

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

A variable that is used to calculate the subsequent cycle steps can be used inside it to call a function with the corresponding parameters.

For (int i \u003d 10; i\u003e 0; i-) (serial.print (i); // numbers 11,9,8,6,5,5,4,3,2,1 will come)

Wheel operator

The For cycle is ideal where we want to calculate. In a situation where you need to perform certain actions as a result of a single event that is not necessarily predictable (for example, we are waiting for the button to press the button), then we can use the WHILE statement that performs the operator block until the condition is performed. The Whole operator syntax looks like this:

While (condition) (// block of instructions for execution)

It is important that the validation of the state takes place at the beginning of the cycle. Can happen so that the instructions inside wheel cycle Never execute. In addition, it is possible to create an infinite cycle. Let's see two examples:

Int x \u003d 2; While (x\u003e 5) (serial.print (x);) -------------- int y \u003d 5; While (Y\u003e 0) (serial.print (y);)

The first block of operators, located inside the While will never be completed. The variable X matters two and it will not become more 5. In the second example, we are dealing with an infinite cycle. The variable "Y" has a duration of 5, i.e. more zero. Inside the cycle, no change in the variable "Y" does not occur, so the cycle will never be completed.

This is a common error when we forget about changing the parameter that causes the termination of the cycle. Below are two correct examples of the application of the WHILE cycle:

Int x \u003d 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 verified in the condition. As a result, the cycle will ever be completed. In the second example, an infinite cycle was deliberately created. This cycle is equivalent to the LOOP () function in Arduino IDE. In addition, inside the cycle, a test was entered, after executing which the cycle is completed by the Break command.

Operator Do ... While

Whether the While cycle is a DO ... While cycle. In addition to the syntax, it is characterized by a place of verification of the condition. In the case of Do ... While Checking the Conditions are made after the execution of the instruction block. This means that the block of instructions in the cycle body will be performed at least once. Below is the syntax of the DO ... While command:

Do (// Instructions block) While (Condition)

All that is written about the WHILE operator also applies to Do ... While. Below is an example of using the DO cycle ... While:

Int x \u003d 10; do (// block of instructions x-;) while (x\u003e 0); -------------- do (// IF instruction block (condition) Break;) While (True);

Operator Break

The BREAK operator allows you to exit the cycle (Do ... While, For, While) and exit the Switch option. In the following example, consider the execution of the Break command:

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

The cycle must be executed for numbers from 0 to 9, but for Numbers 5, a condition is running that runs the BREAK operator. This will lead to the output from the cycle. As a result, only numbers 0.1,2,3,4 will be sent to the serial port (serial.print).

CONTINUE operator

The Continue operator causes termination of the execution of the cycle instructions (Do ... While, For, While) for the current value and the transition to the next cycle step. The following example shows how the Continue operator works:

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

It is not difficult to notice, the cycle will be completed for a value from 0 to 9. For value 5, the Continue command will be executed, as a result of which the instructions that are completed after this command are fulfilled. As a result, the number of 0.1,2,3,4,6,7,8,9 is sent to the serial port (serial.print).

Operator Return

The Return statement completes the execution of the called function and returns the value of a specific type. As a command parameter, you can specify a number, character or variable of a certain type. It is important that the return value corresponds to the type of stated function. The following example shows how to use the Return statement:

Int checksensor () (if (analogread (0)\u003e 400) (// Reading analog input RETURN 1; // For values \u200b\u200bMore than 400 returns 1 ELSE (Return 0; // for others Returns 0))

As you can see, in one function you can use several RETURN operators, but only one of them will always work. It is permissible to use the RETURN operator without parameters. This allows early termination of the function that does not return any value.

Void_name_name () (instruction1; if (x \u003d\u003d 0) Return; instruction2; instruction3;)

In the example above, the instruction1 will always perform when the function is called. The execution of the instruction2 and the instruction3 depends on the result of the IF command. If the condition is executed (true), the RETURN command will be executed and the function will complete the work.

In the case when the condition is not executed, the RETURN command is also not executed, but instructions are executed. Instructions2 and instruction3, and then the function completes its operation.

Goto operator

From ideological considerations you need to skip this description ... Goto operator is a command that should not be used in conventional programming. It raises complication code and is a bad habit in programming. We strongly recommend not to use this command in your programs. Due to the fact that Goto has in the official documentation on the Arduino.cc website, we give it a brief description. Goto command syntax:

.... Goto Metka; // Go to the string with the inscription 'Metka' ... .. .... .... Metka: // Tag with which the program will continue to work ...

The command allows the transition to the label indicated, that is, to the place in the program.

This lesson gives minimal knowledge necessary for programming Arduino systems in C. You can only view it and further use as reference information. Those who programmed on C in other systems you can skip the article.

I repeat that this is the minimum information. Description of pointers, classes, string variables, etc. will be given in subsequent lessons. If something is incomprehensible, do not worry. In further lessons there will be many examples and explanations.

The structure of the Arduino program.

The structure of the Arduino program is quite simple and in the minimum embodiment consists of two parts of the setup () and loop ().

void setup () (

void loop () (

The setup () function is performed once, when you turn on the power or discharge of the controller. Usually it occurs in the initial settings of variables, registers. The function must be present in the program, even if there is nothing.

After completing the setup (), control goes to the LOOP () function. She performs commands recorded in her body in an infinite cycle (between curly brackets). Actually these teams and make all algorithmic actions of the controller.

Initial Syntax Rules C.

; semicolon Expressions may contain many spaces, string portes. A sign of completion of the expression is the "point with a comma" symbol.

z \u003d x + y;
z \u003d X.
+ y;

() Figure brackets Define a block of function or expressions. For example, in the setup () and loop () functions.

/ * ... * / Comment blockBe sure to close.

/ * This is an comment block * /

// Single-line comment, it is not necessary to close, valid until the end of the line.

// This is one row comment

Variables and data types.

Variable is a cell random access memoryin which information is stored. The program uses variables to store intermediate calculation data. For computations, data from different formats, different bit, so the variables in the language C have the following types.

Data type Bit Range of numbers
boolean. 8 true, False
char. 8 -128 … 127
unsigned Char. 8 0 … 255
byte 8 0 … 255
int. 16 -32768 … 32767
unsigned int. 16 0 … 65535
word. 16 0 … 65535
long. 32 -2147483648 … 2147483647
unsigned Long. 32 0 … 4294967295
short 16 -32768 … 32767
float. 32 -3.4028235+38 … 3.4028235+38
double. 32 -3.4028235+38 … 3.4028235+38

Data types are selected based on the desired accuracy of calculations, data formats, etc. Do not, for example, for a counter that considers up to 100, choose type LONG. It will work, but the operation will take more data memory and programs, will require more time.

Announcement of variables.

The data type is indicated, and then the name of the variable.

int x; // Announcement of a variable named X type int
float widthbox; // Announcement of a variable named widthbox type Float

All variables must be declared before they are used.

The variable can be declared in any part of the program, but it depends on which software blocks can be used. Those. Variables have scope areas.

  • Variables declared at the beginning of the program before the Void Setup () function are considered global and available anywhere in the program.
  • Local variables are declared inside the functions or blocks such as the FOR cycle, and can only be used in the declared blocks. There are several variables with one name, but different areas of visibility.

iNT MODE; // variable is available to all functions

void setup () (
// Empty block, the initial installations are not required
}

void loop () (

lONG COUNT; // Count Variable is available only in LOOP () functions.

for (int i \u003d 0; i< 10;) // переменная i доступна только внутри цикла
{
I ++;
}
}

When declaring the variable, you can specify its initial value (initialize).

int x \u003d 0; // A variable x is declared with an initial value of 0
cHAR D \u003d 'A'; // A variable D is declared with the initial value equal to the symbol code "A"

In arithmetic operations with different types of data, the data types are automatically converted. But it is better to always use an explicit transformation.

int x; // Variable int.
char Y; // Variable Char.
int z; // Variable int.

z \u003d x + (int) y; // variable y is clearly converted to int

Arithmetic operations.

Relationship operations.

Logic operations.

Operations on pointers.

Bit operations.

& AND
| OR
^ Excluding or
~ INVERSION
<< Shift left
>> Shift to the right

Mixed assignment operations.

Select options, program management.

IF operator Checks the condition in brackets and performs a subsequent expression or block in curly brackets, if the condition is true.

if (x \u003d\u003d 5) // if x \u003d 5, then z \u003d 0
z \u003d 0;

if (x\u003e 5) // if X\u003e
(z \u003d 0; y \u003d 8;)

If ... Else Allows you to choose between two options.

if (x\u003e 5) // if x\u003e 5, then the block z \u003d 0, y \u003d 8 is performed;
{
z \u003d 0;
y \u003d 8;
}

{
z \u003d 0;
y \u003d 0;
}

ELSE if. - allows you to make a multiple choice

if (x\u003e 5) // if x\u003e 5, then the block z \u003d 0, y \u003d 8 is performed;
{
z \u003d 0;
y \u003d 8;
}

eLSE if (x\u003e 20) // If x\u003e 20, this unit is executed
{
}

eLSE // Otherwise this unit is performed.
{
z \u003d 0;
y \u003d 0;
}

Switch Case. - Multiple choice. Allows you to compare the variable (in the example it x) with several constants (in Example 5 and 10) and perform a block in which the variable is equal to the constant.

switch (x) (

case 5:
// code is performed if x \u003d 5
Break;

case 10:
// code is performed if x \u003d 10
Break;

default:
// Code is performed if no previous value coincided
Break;
}

Cycle for. The design allows you to organize cycles with a given number of iterations. Syntax looks like this:

for (action before the cycle start;
condition continuation of the cycle;
Action at the end of each iteration) (

// Code Code Cycle

An example of a cycle of 100 iterations.

for (i \u003d 0; i< 100; i++) // начальное значение 0, конечное 99, шаг 1

{
Sum \u003d Sum + I;
}

While cycle. The operator allows you to organize cycles with a design:

while (expression)
{
// Code Code Cycle
}

The cycle is performed as long as the expression in brackets is true. An example of a cycle for 10 iterations.

x \u003d 0;
while (X.< 10)
{
// Code Code Cycle
x ++;
}

Do while - cycle with condition at the output.

do.
{
// Code Code Cycle
) While (expression);

The cycle is performed until the expression is true.
Break - Output operator from the cycle. Used to interrupt the execution of the FOR, WHILE, DO WHILE cycles.

x \u003d 0;
while (X.< 10)
{
if (z\u003e 20) Break; // if z\u003e 20, then get out of the cycle
// Code Code Cycle
x ++;
}

Goto. - unconditional transition operator.

goto Metka1; // Transition to Metka1
………………
metka1:

Continue. - skip operators to the end of the cycle body.

x \u003d 0;
While (X.< 10)
{
// Code Code Cycle
if (z\u003e 20) Continue; // If z\u003e 20, then return to the beginning of the body of the cycle
// Code Code Cycle
x ++;
}

Arrays.

An array is a memory area where several variables are sequentially stored.

An array is declared.

int ages; // Array of 10 variables type int

float Weight; // Array of 100 variables type Float

When declaring arrays can be initialized:

iNT AGES \u003d (23, 54, 34, 24, 45, 56, 23, 23, 27, 28);

Apply to variables of arms like this:

x \u003d AGES; // X is assigned a value of 5 array element.
AGES \u003d 32; // 9 An array element is set to 32

The numbering of array elements is always from scratch.

Functions.

Functions allow you to perform the same actions with different data. The function has:

  • the name for which it is caused;
  • arguments - data that the function uses to calculate;
  • data type returned by function.

The user function is described outside the setup () and loop () functions.

void setup () (
// code executed once when starting the program
}

void loop () (
// Main code, performed in the cycle
}

// Announcement of a user function named FunctionName
Type FunctionName (Type Argument1, Type Argument1, ..., Type Argument)
{
// body function
Return ();
}

An example of a function calculating the sum of the squares of two arguments.

iNT SUMQWADR (INT X, INT Y)
{
Return (x * x + y * y);
}

The function call is happening:

d \u003d 2; b \u003d 3;
z \u003d sumqwadr (d, b); // in Z will be the sum of the squares of the variables D and B

Functions are built-in, custom, connected.

Very short, but this data should be enough to start writing programs on C for Arduino systems.

The last thing I want to tell in this lesson, as is customary to execute programs on C. I think if you read this lesson for the first time, it is worth skipping this section and return to it later when it will make it possible.

The main goal of external program design is to improve the readability of programs, reduce the number of formal errors. Therefore, to achieve this goal, you can safely violate all the recommendations.

Names in C.

Names representing data types must be written in a mixed register. The first letter of the name must be the title (top register).

Signal, TimeCount

Variables must be recorded by names in the mixed register, the first letter of the line (lower case).

Rubric :. You can add to bookmarks.

After familiarization with the main elements of Arduino, as well as writing the program "Hello World!" It's time for familiarizing the programming language.

The structure of the language is mainly based on C / C ++, so those who have previously programmed in this language will not have difficulty leaving Arduino programming. The rest should learn the basic information about management commands, data types and functions.

Most of the information contained herein will be compatible with any C / C ++ course, taking into account differences in data types, as well as several specific instructions for programming I / O ports.

Basics of the basics

Several formal things, that is, those that everyone knows, but sometimes forget ...

In Arduino IDE, as in C / C ++, you must remember the registers of characters. Keywords, such as if, for are always written in the lower case. Each instruction ends on ";". A semicolon reports a compiler, which part to interpret as an instruction.

Brackets (..) are used to designate software blocks. We use them to limit the body function (see below), cycles and conditional operators.

Good practice is to add comments to the contents of the program, it helps to easily understand the code. Single-line comments begin with // (Double sinking line). Multi-line comments begin with /* and end on */

If we want to connect any library into our program, we use the Include command. Here are examples of linking libraries:

#Include. // Standard library #include "svoya_biblioteka.h" // Library in the project catalog

Functions in Arduino

The function (subroutine) is a separate part of the program that performs some operations. Functions are used to simplify the main program and improve the readability of the code. Useful to use functions as we can easily use them in many of our projects.

The standard programming course contains information about the functions that give the following articles. In the case of Arduino, the functions will be discussed at the beginning, because even the simplest program should have two special functions. It has already been mentioned in previous articles, but here we systematize this information.

Defense ad

The declaration scheme features as follows:

Function_name type (parameter) (// Instructions for execution (body function) RETURN (/ * Return value * /);)

a type - This is the name of any available data type on this language Programming. List of types available when programming Arduino Let's see in a separate article.

After execution, the function will return the value of the announced type. In case the function does not accept any return value, the data type will be "void".

function name Allows it to unambiguously identify. In order to call (run) function, we give her a name.

parameter - Function call parameter. Parameters are not required, but often they are useful. If we write a function that has no arguments, we leave round brackets empty.

Inside the brackets "(...)" contains the actual body of the function or the instructions that we want to perform. Description of specific instructions indicate in a separate article.

All functions that return to the value are completed by the Return operator, followed by the return value. Only functions declared by zero pointer ("void") do not contain the RETURN operator. It is necessary to know that the RETURN statement completes the performance of the function regardless of the location.

Below are some examples of declarations of functions.

Void F1 () (// body function) -------------- int minus () (// body function RETURN (0);) ----------- --- INT PLUS (INT A, INT B) (RETURN (A + B);)

As you can see on the examples, the declaration of functions can take various forms depending on your needs.

We strongly recommend that you explore and apply functions when writing your own programs. Over time, each programmer gains its own library of functions "for all occasions", which makes it easier and speed up the process of writing new programs.

Now that we know how you can write your own function, you need to learn to use it.

Call function

All functions we record in one file / program. There is of course a more elegant solution, but we will try to describe it next time.

Announces the function, we can use it in other functions with the corresponding name and any required parameters. Below are examples of calling the functions that we led to above:

F1 (); Plus (2.2); y \u003d plus (1.5);

As you can see in examples, the function call is performed by specifying its name and the required number of parameters. It is important to always call a function in accordance with its announcement.

If the function F1 () is declared without parameters, then no parameters cannot be specified when it is called, i.e. Calling the function F1 (0) will be incorrect.

The PLUS function (int a, int b) requires exactly two parameters, so the call with one or three parameters is impossible.

The call y \u003d plus (1.5) will be executed with the "Plus" function with the parameters "1" and "5" and save the return value to the "Y" variable.

SETUP () and LOOP () functions.

Having knowledge of declaring and calling functions, we can go to the ARDUINO system functions: setup () and loop (). Arduino IDE B. obligatory It is necessary to declare these two functions.

setup () is a function that is called automatically when the power is turned on or pressing the RESET button.

In accordance with its name, it is used to set the initial values \u200b\u200bof variables, the inputs and system outputs, which are usually set in the initial parameters. Thanks to its specificity, this feature does not return values \u200b\u200band is not called with parameters. The correct setup () function declaration is presented below:

Void setup () (// body function - system initialization)

loop () is a function that is called in an infinite cycle. This feature also does not return values \u200b\u200band is not called with parameters. The correct declaration of the LOOP () function is shown below.

Void loop () (// body function - program code)

As you can see, declaring the LOOP () function is identical to the declaration of the setup () function. The difference is to perform these functions with a microcontroller.

Now we analyze the following pseudocode:

Void setup () (on_led1 (); // turn on the LED1 OFF_LED1 () LED; // turn off the LED1 LED1) void loop () (on_led2 (); // turn on the LED2 OFF_LED2 () LED; // Turn off the LED2 LED)

In the setup () function there are two instructions: the first turns on the LED1 LED connected to the board (for example, contact 13), and the second turns off the LED1 LED.

The LOOP () function has identical instructions for turning on and off the LED2 LED connected to the board (for example, contact 12).

As a result of the launch of the LED1 LED program, the LED will blink once, while LED2 will light up and go out until Arduino is turned on.

Pressing the RESET button will lead to the fact that LED1 will flash again once, and LED2 will again begin to flash.

Summarize:

  • SETUP () and LOOP () functions are system functions that must be defined in each project. Even in a situation where in one of them we do not write any code, we still have to declare these two functions;
  • The setup () function is executed once, LOOP () is performed continuously;
  • We create own functions in one file;
  • We can call our functions from both setup () and loop () and from other functions;
  • Our own functions can be called with parameters and return value;
  • The function call must be performed in accordance with its declaration.

The basis of the Arduino module programming language is the SI language (rather S ++). More precisely, this language dialect is called Processing / Wiring. Good Language Review You will find in the application. And I want to tell more not about the language, but about programming.

The program is a kind of set of commands that the processor understands the processor of your computer or the Arduino module microcontroller processor is not important. The processor reads the commands and performs them. Any teams that the processor understand are binary numbers. These are only binary numbers and nothing else. By performing arithmetic operations for which the processor is once and intended, the processor operates with numbers. Binary numbers. And it turns out that both the teams, and what they belong to is just binary numbers. Like this. But how does the processor understand this "pile" binary numbers?

First, all these binary numbers are written to serial memory cells that have addresses. When you download the program, and it starts to work, the processor receives the first address of the program, where the command must be recorded. Those commands that require processor operations with numbers have "identifying signs", for example, that in the following two memory cells two numbers that need to be folded. And the counter, calling his meter of commands, where the address of the next command is recorded, in this case increases the address so that the program will have the following command in this address. If the program or failures of the program or failures, the processor may be mistaken, and then, after reading the number instead of the team, the processor does not do something that should do, and the program "freezes".

Thus, any program is a sequence of binary numbers. And programming is the ability to correctly record the correct sequences of binary numbers. For a long time, it began to use special tools that are called programming languages.

However, any program first of all requires you a clear understanding of what the program should do, and for what it is needed. The clearer you understand this, the easier it is to create a program. Small programs, although it is difficult to say which programs are small, and which are not, can be considered entirely. More complex programs are better divided into parts that can be viewed as independent programs. So it is better to create, easier to debug and check.

I am not ready to argue, but I think that the program is more convenient to start with descriptions in the usual language. And in this sense, I believe that programming should not be confused with writing the program code. When the program is described by conventional words, it is easier for you to determine, for example, what programming language to select to create a program code.

Closest to record the program using binary numbers, the assembler language. It is characterized by the compliance of the language commands to binary teams, understandable processor. But the encoding of programs on the assembler requires great effort and closer to art than to formal operations. More versatile and easier to apply high-level languages \u200b\u200bas Baisik or C. And for a long time, a graphic language is used to record programs in general, and recently "translators" have appeared from this language to the processor language.

In addition to language programming languages, there has always existed some specialization of programming languages, and existed specialized languages. The last I would also take the Arduino module programming language.

All you need to say the module so that it makes something necessary to us, organized in a convenient set of commands. But at first about what we need from Arduino?

The module can be used in different qualities - this is the heart (or head) of the robot, it is the basis of the device, this is a convenient designer to master working with microcontrollers, etc.

Above, we have already used simple programs to check the module connection to the computer. Someone may seem too simple, and therefore not interesting, but any complex programs consist of simpler fragments similar to those with whom we have already acquainted.

Let's see what we can tell us the most simple program "Complete LED".

int ledpin \u003d 13;

pinmode (Ledpin, Output);

digitalWrite (LEDPIN, HIGH);

digitalWrite (Ledpin, Low);

First, let's remember what LED is. In essence, this is an ordinary diode that, due to its design, when the current flows in the forward direction, the transition begins. That is, that the LED is lit, you need to flow through it, and, it means that the LED should be applied to the LED. And so that the current does not exceed the permissible value, in series with the LED, a resistor should be included, which is called current-limiting (see Appendix A, digital output). The voltage to the LED applies a microcontroller, which is the basis of the Arduino module. The microcontroller, except the processor that performs our commands, has one or more I / O ports. Without going into consideration specific device Port, let's say - when the port output works on the output, it can be represented as a digital chip output with two states, turned on and off (there is a voltage at the output, no voltage at the output).

But the same port output can also work as an entrance. In this case, it can be submitted, for example, like a digital chip input - a logical level, high or low (see Appendix A, digital input).

As we blink the LED:

Enable port output. Turn off the port output.

But the processor works very quickly. We will not have time to see blinking. To see this blinking, we need to add pauses. I.e:

Enable port output. Pause 1 second.

Turn off the port output.

Pause 1 second.

This is our program. The processor reads the first command and turns on the output, the LED will light up. The processor then will pause in operation and turn off the output, the LED will go out. But he blinked only once.

Repetition of any process or set commands is called a cycle programming. Used different types of cycles. There is a cycle that is performed set number time. This is a Cycle for. There are cycles that are executed until a condition is performed, which is part of the language design of the cycle. And if the condition is never completed, the cycle is performed an infinite number of times. This is an infinite cycle.

I do not think that microcontrollers are used with the programs of the type, which is above. That is, several commands are executed once and the controller does not work. As a rule, it works constantly as soon as the supply voltage is supplied. And, it means that the microcontroller should work in an infinite cycle.

This is what the function void loop (), Loop is a loop, a closed cycle. The conditions for termination of the cycle is not, and, therefore, there is no condition for its completion.

In addition, we must report Arduino module, which port output and how we want to use, to exit (OUTPUT) or input (INPUT). This goal is the Void Setup () function, which is mandatory for the Arduino language, even if it is not used, and the Pinmode () command (), to specify the output mode.

pinmode (Ledpin, Output);

And yet, the language design uses variables to determine the output number:

int ledpin \u003d 13;

Using variables is convenient. Deciding that you will use no output 13, and 12, you will make a change only in one line. It is especially strongly affected in large programs. The variable name can be chosen at its discretion, but, as a rule, it should only be symbol, and often the number of characters is limited. If you misinterpret the name of the variable, I think the compiler will correct you.

The DigitalWrite feature (LEDPIN, HIGH) sets the specified output to a high level state, that is, it turns on the output.

And Delay (1000), as you already understood, means pause in 1000 milliseconds or 1 second.

It remains to understand what the consoles such as int, void. Any values, any variables are placed in memory as the program commands. In the memory cells, numbers are often written out of 8 bits. This is byte. But byte is numbers from 0 to 255. To write large numbers you need two bytes or more, that is, two or more memory cells. In order for the processor to be clear how to find a number, different types Numbers have different names. So the number named byte, will take one cell, int (integer, integer) more. In addition, the functions used in programming languages \u200b\u200bare also returned by the numbers. To determine which type of number must return a function, this type of returned number is recorded before function. But some functions may not return numbers, such functions are preceded by the Void entry (see Appendix A, Variables).

This is how much an interesting program can tell.

All of this you hope you read in the application. And now we will do simple experiments using only what we already know from the ability of the language. First, replace variable type INT, which takes a lot of space in memory, on Byte - one place, one memory cell. Let's see what we succeed.

byte ledpin \u003d 13;

pinmode (Ledpin, Output);

digitalWrite (LEDPIN, HIGH);

digitalWrite (Ledpin, Low);

After compiling and downloading the program to the module, we will not note the changes in the program. Okay. Then I will change the program to notice changes in its work.

To do this, we will replace the number in the function of the Delay (1000) variable, calling it my_del. This variable must be an integer, that is, Int.

int my_del \u003d 5000;

Do not forget to finish each team with a comma. Make changes to the program, compile it and boot into the module. Then change the variable and repeat the compilation and loading:

byte my_del \u003d 5000;

The difference, I am sure you will get tangible.

We will do another experiment with changing the duration of the pause. Reducing the duration of the pauses will be performed, say, five times. We will pause for 2 seconds, and then we will increase the same five times. And again we will pause for 2 seconds. The cycle performed specified number of times is called cycle for And he is written so:

for (int i \u003d 0; i<5; i++)

something that is performed in the Cycle for

To execute the cycle, it needs a variable, we have this i, the variable you need to set the initial value that we have appropriated. Then follows the condition of completing the cycle, we have less than 5. And I ++ recording is characteristic of the C record of an increase in the variable per unit. Figure brackets limit the set of commands to be executed in the FOR cycle. In other programming languages, there may be other limiters to highlight the function code block.

Inside the cycle, we carry out the same as before, with minor changes:

for (int i \u003d 0; i<5; i++)

digitalWrite (LEDPIN, HIGH);

digitalWrite (Ledpin, Low);

my_del \u003d my_del - 100;

We talked about changing the recording of the pause, and the change in the pause itself is achieved by a decrease in the variable by 100.

For the second cycle, we will write the same block of code, but the variable of the pause duration will increase by 100.

for (int i \u003d 0; i<5; i++)

digitalWrite (LEDPIN, HIGH);

digitalWrite (Ledpin, Low);

You noticed that the recording of a decrease in the pause and its increase look different. This is also a feature of the SI language. Although for clarity, it was necessary to repeat this entry by changing only the minus sign on the plus. So, we get such a program:

int ledpin \u003d 13;

int my_del \u003d 1000;

pinmode (Ledpin, Output);

for (int i \u003d 0; i<5; i++)

digitalWrite (LEDPIN, HIGH);

digitalWrite (Ledpin, Low);

for (int i \u003d 0; i<5; i++)

digitalWrite (LEDPIN, HIGH);

digitalWrite (Ledpin, Low);

Copy the code of our program in the Arduin program, compile it and drive it into the module. Changing the duration of the pause is noticeable. And it will be even more noticeable, try, if you finish the FOR cycle, say, just 8.

What we have done now is doing and professional programmers - having a ready-made program, it can be easily modified under your needs or desires. Therefore, they store all their programs. What I advise you to do and you.

What have we missed in your experiment? We did not comment on our work. To add a comment, either a double "straight" oblique line, or single, but with stars (see Appendix A). I advise you to do it yourself, because by returning to the program after a while you are easier to figure it out if you are explained that you are doing in a particular place of the program. And I also advise it in a folder with each program to store its description in the usual language, made in any text editor.

The simplest program to "freeze the LED" can serve even for a dozen experiments (even with one LED). It seems to me this part of the work, invent that you can still make an interesting, most interesting. If you refer to the application where the programming language is described, to the "Program Management" section, you can replace the for cycle for another type of cycle. And try how other types of cycles work.

Although the microcontroller processor, like any other, can produce calculations (for that and invented it), and this is used, for example, in devices, still the most characteristic operation for the microcontroller will be setting the port output to a high or low state, that is, " Make a LED ", as a reaction to external events.

About external events The microcontroller will know mainly at the state of the entrances. Configuring the port conclusions to the digital input, we can follow it. If the initial input state is a high level, and the event causes the login to enter a low state, then we can do something, responding to this event.

The easiest example is the button input. When the button is not pressed, input in high condition. If you press the button, the input goes into a low state, and we can "ignite" the outlet LED. The next time you press the LED button you can pay off.

This is a simple example of a simple program. Even beginner, she may seem uninteresting. However, this simple program can find quite useful use. I will give only one example: we will not light the LED after clicking on the button, but merging (in a certain way). And the LED will take with infrared radiation. As a result, we will get the control panel. Here is such a simple program.

In different versions of the program there are differences in the list of examples. But you can refer to the language manual in the application where there is an example and scheme of the program (in the examples section called "Appendix") to work with the introduction. I will copy the program:

int ledpin \u003d 13;

pinmode (Ledpin, Output);

pinmode (Inpin, Input);

if (Digitalread (Inpin) \u003d\u003d HIGH)

digitalWrite (LEDPIN, HIGH);

digitalWrite (Ledpin, Low);

And, as you see, we get a completely new program, modifying the old one. Now the LED will flash only when the button is pressed, which is attached to the output 2. Conclusion 2 through a resistor 10 kΩ is attached to the general wire (land, GND). The button is one end attached to the supply voltage + 5V, and another end to the output 2.

In the program, we meet a new Language structure if from the Program Management section. It is read like this: if a condition is satisfied (enclosed in brackets), then the program is executed in the curly brackets. Please note that in the condition (DigitalRead (INPIN) \u003d\u003d HIGH) the equality of the input is highly executed using two equality signs! Very often in a hurry about it is forgotten, and the condition is incorrect.

The program can be copied and downloaded to the Arduino module. However, to check the operation of the program, you need to make some changes to the design of the module. However, it depends on the variety of the module. The original module has a socket for connecting to the extension boards. In this case, you can insert suitable single-core wires to the desired connectors. My module has knife contacts to connect with extension boards. I can either look for a suitable connector, or, which is cheaper, use the appropriate microcircuit panel in the DIP case.

The second question - how to find the conclusions from the module that are used in the program?

With this question will help to figure out the picture I took from the site: http://roobocraft.ru/.

Fig. 4.1. Location and purpose of the conclusions of the controller and the Arduino module

All conclusions of my CraftDUINO module are marked, so finding the right conclusion will not be difficult. You can connect the button and resistor and check the operation of the program. By the way, on the aforementioned site Robocraft, the entire process is displayed in the pictures (but the program uses not quite such conclusions!). I advise you to look.

Many microcontrollers in their composition have additional hardware devices. So ATMEGA168, on the basis of which the Arduino module assembled has a UART, a built-in block for communication with other devices using a consistent data exchange. For example, with a computer through the COM port. Or with another microcontroller using its built-in UART unit. There is also an analog-to-digital converter. And latitudinal modulation formator.

The use of the latter illustrates the program that I also copy from the Robocraft site. But the program can be taken from the application. And maybe it is in the examples of the Arduino program.

// Fading Led by Barragan

int value \u003d 0; // variable for storing the desired value

int ledpin \u003d 9; // LED connected to Digital PIN 9

// No need to call the Pinmode function

fOR (Value \u003d 0; Value<= 255; value+=5) // постепенно зажигаем светодиод

analogWrite (LEDPIN, VALUE); // output value (from 0 to 255)

delay (30); // Looking for 🙂

for (Value \u003d 255; Value\u003e \u003d 0; Value- \u003d 5) // Gradually Gasim LED

analogWrite (LEDPIN, VALUE);

If in the previous new program for us there was a DigitalDalread (INPIN) function, reading digital input, then in this program a new feature AnalogWrite (LEDPIN, VALUE) function, although the parameters of this function are already familiar to us variables. On the use of analog input, using the ADC (analog-to-digital converter), we will talk later. And now we will return to the general issues of programming.

Programming is something that is available to everyone, but the time will need to master and programming, and any programming language. Today there are a number of programs that help learn that programming. And one of them is directly related to the Arduino module. It is called Scratch for Arduino or abbreviated S4a. You can find and download this program at: http://seaside.citilab.eu/scratch/arduino. I do not know how the program name is accurately translated, but "To Begin from Scratch" is translated as "start from scratch".

On the S4A project site there are versions for Windows and Linux, but for the latest operating system ready to install the program in the Debian distribution version. I do not want to say that it cannot be used with other Linux distributions, but at first we'll see how to work in the program with the Arduino module in Windows.

After installing the program, the interface into Russian can be configured in the usual way using the language switch.

Fig. 4.2. Program Interface Language Switch

The first toolbar icon if you click, displays all possible program interface languages. Russian language can be found in the section ...

Fig. 4.3. List of languages \u200b\u200bfor use in the program interface

... marked as "more ...".

If you do nothing, then the inscription in the right window "Searching Board ..." remains, but the module is not located. To connect the Arduino module to S4A, you should download something from the project site yet.

Fig. 4.4. File download to the Arduino module for S4A

This file is nothing but a program for Arduino (Sketch). That is, a text file that can be copied to the Arduino editor, compile and upload to the module. After leaving the Arduino program, you can run the S4A program and now the module is located.

Fig. 4.5. Connecting a module to the program

The analog inputs of the module are not connected, as well as digital, therefore the values \u200b\u200bdisplayed for the module are constantly changing randomly.