• What program to program Arduino in. Arduino for beginners: step-by-step instructions. Arduino Programming and Projects: Where to Start

    What does the program consist of?

    To begin with, it is worth understanding that a program cannot be read and written like a book: from cover to cover, top to bottom, line by line. Any program consists of separate blocks. The beginning of a block of code in C/C++ is indicated by a left curly brace ( , its end by a right curly brace ) .

    There are blocks different types and which of them will be executed when depends on external conditions. In the example minimum program you can see 2 blocks. In this example the blocks are called defining a function. A function is simply a block of code with a given name that someone can then use from the outside.

    IN in this case we have 2 functions named setup and loop. Their presence is mandatory in any C++ program for Arduino. They may not do anything, as in our case, but they must be written. Otherwise, you will get an error at the compilation stage.

    Classic of the genre: flashing LED

    Let's now supplement our program so that at least something happens. On Arduino, an LED is connected to pin 13. It can be controlled, which is what we will do.

    void setup() ( pinMode(13 , OUTPUT) ; ) void loop() ( digitalWrite(13 , HIGH) ; delay(100 ) ; digitalWrite(13 , LOW) ; delay(900 ) ; )

    Compile and download the program. You will see that the LED on the board blinks every second. Let's figure out why this code leads to blinking every second.

    Each expression is an order to the processor to do something. Expressions within one block are executed one after another, strictly in order, without any pauses or switching. That is, if we are talking about one specific block of code, it can be read from top to bottom to understand what is being done.

    Now let's understand in what order the blocks themselves are executed, i.e. setup and loop functions. Don’t worry about what specific expressions mean just yet, just observe the order.

      As soon as the Arduino is turned on, flashed or the RESET button is pressed, “something” calls a function setup. That is, it forces the expressions in it to be executed.

      As soon as setup completes, “something” immediately calls the loop function.

      As soon as loop completes, “something” immediately calls the loop function again and so on ad infinitum.

    If we number the expressions in order of how they are executed, we get:

    void setup() ( pinMode(13 , OUTPUT) ; ❶ ) void loop() ( digitalWrite(13 , HIGH) ; ❷ ❻ ❿ delay(100 ) ; ❸ ❼ … digitalWrite(13 , LOW) ; ❹ ❽ delay(900 ) ; ❺ ❾ )

    Let us remind you once again that you should not try to perceive the entire program by reading from top to bottom. Only the contents of the blocks are read from top to bottom. We can generally change the order of the setup and loop declarations.

    void loop() ( digitalWrite(13 , HIGH) ; ❷ ❻ ❿ delay(100 ) ; ❸ ❼ … digitalWrite(13 , LOW) ; ❹ ❽ delay(900 ) ; ❺ ❾ ) void setup() ( pinMode(13 , OUTPUT ) ; ❶ )

    The result from this will not change one iota: after compilation you will get an absolutely equivalent binary file.

    What Expressions Do

    Now let's try to understand why the written program ultimately causes the LED to blink.

    As you know, Arduino pins can work as both outputs and inputs. When we want to control something, that is, issue a signal, we need to switch the control pin to the output state. In our example, we control the LED on the 13th pin, so the 13th pin must be made an output before use.

    This is done by an expression in the setup function:

    PinMode(13 , OUTPUT) ;

    Expressions can be different: arithmetic, declarations, definitions, conditionals, etc. In this case, we implement in the expression function call. Remember? We have their the setup and loop functions, which are called by something we called "something". So now We we call functions that are already written somewhere.

    Specifically in our setup we call a function called pinMode. It sets the pin specified by number to the specified mode: input or output. We indicate which pin and which mode we are talking about in parentheses, separated by commas, immediately after the function name. In our case, we want the 13th pin to act as an output. OUTPUT means output, INPUT means input.

    Qualifying values ​​such as 13 and OUTPUT are called function arguments. It is not at all necessary that all functions must have 2 arguments. How many arguments a function has depends on the essence of the function and how the author wrote it. There can be functions with one argument, three, twenty; functions can have no arguments at all. Then to call them, the parenthesis is opened and immediately closed:

    NoInterrupts() ;

    In fact, you may have noticed that our setup and loop functions don't take any arguments either. And the mysterious “something” calls them up in the same way with empty parentheses at the right moment.

    Let's return to our code. So, since we plan to blink the LED forever, the control pin needs to be made an output once and then we don't want to remember about it. This is what the setup function is ideologically intended for: setting up the board as needed and then working with it.

    Let's move on to the loop function:

    void loop() ( digitalWrite(13, HIGH) ; delay(100) ; digitalWrite(13, LOW) ; delay(900) ; )

    As mentioned, it is called immediately after setup . And it is called again and again as soon as it ends. The loop function is called the main loop of the program and is ideologically designed to perform useful work. In our case useful work- blinking LED.

    Let's go through the expressions in order. So the first expression is a call to the digitalWrite built-in function. It is designed to apply a logical zero (LOW, 0 volts) or a logical one (HIGH, 5 volts) to a given pin. Two arguments are passed to the digitalWrite function: pin number and boolean value. As a result, the first thing we do is light the LED on the 13th pin, applying 5 volts to it.

    As soon as this is done, the processor immediately proceeds to the next expression. For us, this is a call to the delay function. The delay function is, again, a built-in function that makes the processor sleep for a certain time. It takes just one argument: the time in milliseconds to sleep. In our case it is 100 ms.

    While we sleep, everything remains as it is, i.e. the LED remains lit. As soon as the 100 ms expires, the processor wakes up and immediately moves on to the next expression. In our example, this is again a call to the familiar digitalWrite built-in function. True, this time we pass the value LOW as the second argument. That is, we set a logical zero on the 13th pin, that is, we supply 0 volts, that is, we turn off the LED.

    After the LED is extinguished we proceed to the next expression. Once again this is a call to the delay function. This time we fall asleep for 900 ms.

    Once sleep is over, the loop function exits. Upon completion, “something” immediately calls it again and everything happens again: the LED lights up, lights up, goes out, waits, etc.

    If you translate what is written into Russian, you get the following algorithm:

      Lighting up the LED

      Sleep for 100 milliseconds

      Turning off the LED

      We sleep for 900 milliseconds

      Let's go to point 1

    Thus we got an Arduino with a beacon blinking every 100 + 900 ms = 1000 ms = 1 second.

    What can be changed

    Let's use only the knowledge we have gained to make several variations of the program to better understand the principle.

    You can connect an external LED or other device that needs to "blink" to a different pin. For example, on the 5th. How should the program change in this case? We must replace the number with the 5th one wherever we accessed the 13th pin:

    Compile, download, test.

    What needs to be done to make the LED flash 2 times per second? Reduce sleep time so that the total is 500 ms:

    void setup() ( pinMode(5 , OUTPUT) ; ) void loop() ( digitalWrite(5 , HIGH) ; delay(50 ) ; digitalWrite(5 , LOW) ; delay(450 ) ; )

    How can I make the LED flicker twice every time it blinks? You need to light it twice with a short pause between turns on:

    void setup() ( pinMode(5 , OUTPUT) ; ) void loop() ( digitalWrite(5 , HIGH) ; delay(50 ) ; digitalWrite(5 , LOW) ; delay(50 ) ; digitalWrite(5 , HIGH) ; delay (50 ) ; digitalWrite(5 , LOW) ;

    How can I make the device have 2 LEDs that blink alternately every second? You need to communicate with two pins and work in a loop with one or the other:

    void setup() ( pinMode(5 , OUTPUT) ; pinMode(6 , OUTPUT) ; ) void loop() ( digitalWrite(5 , HIGH) ; delay(100 ) ; digitalWrite(5 , LOW) ; delay(900 ) ; digitalWrite (6 , HIGH) ; delay(100 ) ; digitalWrite(6 , LOW) ;

    How to make sure that the device has 2 LEDs that switch like a railway traffic light: first one then the other lights up? You just need to not turn off the lit LED right away, but wait until the moment of switching:

    void setup() ( pinMode(5 , OUTPUT) ; pinMode(6 , OUTPUT) ; ) void loop() ( digitalWrite(5 , HIGH) ; digitalWrite(6 , LOW) ; delay(1000 ) ; digitalWrite(5 , LOW) ; digitalWrite(6 , HIGH) ; delay(1000 ) ;

    Feel free to check out other ideas yourself. As you can see, it's simple!

    About empty space and beautiful code

    In C++, spaces, line breaks, and tab characters do not have of great importance for the compiler. Where there is a space, there may be a line break and vice versa. In fact, 10 spaces in a row, 2 line breaks and 5 more spaces are the equivalent of one space.

    Empty space is a programmer’s tool with which you can either make a program understandable and visual, or disfigure it beyond recognition. For example, remember the program for blinking an LED:

    void setup() ( pinMode(5 , OUTPUT) ; ) void loop() ( digitalWrite(5 , HIGH) ; delay(100 ) ; digitalWrite(5 , LOW) ; delay(900 ) ; )

    We can change it like this:

    void setup( ) ( pinMode(5 , OUTPUT) ; ) void loop () ( digitalWrite(5 ,HIGH) ; delay(100 ) ; digitalWrite(5 ,LOW) ; delay(900 ) ; )

    All we did was work a little with the empty space. Now you can clearly see the difference between harmonious code and unreadable code.

    To follow the unspoken law of program design, which is respected on forums, when read by other people, and is easily perceived by you, follow a few simple rules:

    1. Always increase the indentation between ( and ) when starting a new block. Typically 2 or 4 spaces are used. Choose one of the values ​​and stick to it throughout.

    Badly:

    void loop() ( digitalWrite(5 , HIGH) ; delay(100 ) ; digitalWrite(5 , LOW) ; delay(900 ) ; )

    Fine:

    void loop() ( digitalWrite(5 , HIGH) ; delay(100 ) ; digitalWrite(5 , LOW) ; delay(900 ) ; )

    2. Just like in natural language: put a space after commas and don't put before.

    Badly:

    DigitalWrite(5 ,HIGH) ; digitalWrite(5 , HIGH) ; digitalWrite(5 ,HIGH) ;

    Fine:

    DigitalWrite(5 , HIGH) ;

    3. Place the block start symbol ( on new line at the current indentation level or at the end of the previous one. And the end-of-block character ) on a separate line at the current indentation level:

    Badly:

    void setup() ( pinMode(5, OUTPUT); ) void setup() ( pinMode(5, OUTPUT); ) void setup() ( pinMode(5, OUTPUT); )

    Fine:

    void setup() ( pinMode(5 , OUTPUT) ; ) void setup() ( pinMode(5 , OUTPUT) ; )

    4. Use empty lines to separate blocks of meaning:

    Fine:

    Even better:

    void loop() ( digitalWrite(5 , HIGH) ; delay(100 ) ; digitalWrite(5 , LOW) ; delay(900 ) ; digitalWrite(6 , HIGH) ; delay(100 ) ; digitalWrite(6 , LOW) ; delay( 900 ) ; )

    About semicolons

    You might be wondering: why is there a semicolon at the end of every expression? These are the rules of C++. Such rules are called language syntax. By symbol; the compiler understands where the expression ends.

    As already mentioned, line breaks are an empty phrase for him, so he focuses on this punctuation mark. This allows you to write multiple expressions on one line:

    void loop() ( digitalWrite(5 , HIGH) ; delay(100 ) ; digitalWrite(5 , LOW) ; delay(900 ) ; )

    The program is correct and equivalent to what we have already seen. However, writing like this is bad form. The code is much more difficult to read. So unless you have a 100% good reason to write multiple expressions on the same line, don't do it.

    About comments

    One of the rules of good programming is: “write code so that it is so clear that it does not need explanation.” This is possible, but not always. In order to explain some non-obvious points in the code to its readers: your colleagues or yourself in a month, there are so-called comments.

    These are the designs in program code, which are completely ignored by the compiler and only matter to the reader. Comments can be multi-line or single-line:

    /* The setup function is called very first when power is applied to the Arduino. And this is a multi-line comment */ void setup() ( // set pin 13 to output mode pinMode(13 , OUTPUT) ; ) void loop() ( digitalWrite(13, HIGH) ; delay(100) ; // sleep for 100 ms digitalWrite(13, LOW) ; delay(900) ; )

    As you can see, you can write as many comment lines as you like between the /* and */ symbols. And after the sequence / / everything that follows until the end of the line is considered a comment.

    So, we hope the most basic principles of writing programs have become clear. The knowledge gained allows you to programmatically control the power supply to the Arduino pins according to certain timing schemes. This is not so much, but still enough for the first experiments.

    Ardublock is a graphical programming language for Arduino designed for beginners. This environment is quite easy to use, easy to install, and almost completely translated into Russian. A visually designed program that resembles blocks...

    Interrupts are a very important mechanism in Arduino that allows external devices to interact with the controller when various events occur. By installing a hardware interrupt handler in the sketch, we can respond to a button being turned on or off, a keyboard press,...

    Serial.print() and Serial.println() are the main Arduino functions to transfer information from the Arduino board to the computer via serial port. The most popular Arduino Uno, Mega, Nano boards do not have a built-in display, so...

    Is it possible to do Arduino projects without the Arduino board itself? It turns out, quite. Thanks to numerous online services and programs that have their own name: emulator or Arduino simulator. The most popular representatives of such programs are...

    Serial begin - extremely important instructions Arduino, it allows the controller to establish a connection with external devices. Most often like this external device“It turns out to be the computer to which we connect the Arduino. That's why Serial begin is more intense...

    A global variable in Arduino is a variable whose scope extends to the entire program, it is visible in all modules and functions. In this article we will look at several examples of using global variables...

    Arduino arrays are a language element actively used by programmers to work with sets of data of the same type. Arrays are found in almost all programming languages, Arduino is no exception, the syntax of which is very similar...

    The Arduino programming language for beginners is presented in detail in the table below. The Arduino microcontroller is programmed in special language programming based on C/C++. Language Arduino programming is a variant of C++, in other words, there is no separate programming language for Arduino. Download book PDF possible at the end of the page.

    IN Arduino IDE all written sketches are compiled into a program in C/C++ with minimal changes. The Arduino IDE compiler greatly simplifies writing programs for this platform and creating devices on Arduino becomes much more accessible to people who do not have extensive knowledge of the C/C++ language. Below we will give a short reference describing the main functions of the Arduino language with examples.

    Detailed reference to the Arduino language

    The language can be divided into four sections: statements, data, functions and libraries.

    Arduino language Example Description

    Operators

    setup() void setup()
    {
    pinMode(3, INPUT);
    }
    The function is used to initialize variables, determine the operating modes of pins on the board, etc. The function runs only once, after each power supply to the microcontroller.
    loop() void loop()
    {
    digitalWrite(3, HIGH);
    delay(1000);
    digitalWrite(3, LOW);
    delay(1000);
    }
    The loop function loops around, allowing the program to perform and react to calculations. The setup() and loop() functions must be present in every sketch, even if these statements are not used in the program.

    Control statements

    if
    if(x>
    if(x< 100) digitalWrite (3, LOW );
    The if statement is used in combination with comparison operators (==, !=,<, >) and checks whether the condition is true. For example, if the value of the variable x is greater than 100, then the LED at output 13 turns on; if it is less, the LED turns off.
    if..else
    if (x > 100) digitalWrite (3, HIGH );
    else digitalWrite(3, LOW);
    The else operator allows you to make a check other than the one specified in the if, in order to perform several mutually exclusive checks. If none of the checks receive a TRUE result, then the block of statements in else is executed.
    switch...case
    switch(x)
    {


    case 3: break ;

    }
    Like an if statement, a switch statement controls a program by allowing you to specify actions that will be performed when different conditions. Break is a command to exit a statement; default is executed if no alternative is selected.
    for void setup()
    {
    pinMode(3, OUTPUT);
    }
    void loop()
    {
    for (int i=0; i<= 255; i++){
    analogWrite(3, i);
    delay(10);
    }
    }
    The for construct is used to repeat statements enclosed in curly braces. For example, smooth dimming of an LED. The for loop header consists of three parts: for (initialization; condition; increment) - initialization is performed once, then the condition is checked, if the condition is true, then the increment is performed. The loop repeats until condition becomes false.
    while void loop()
    {
    while(x< 10)
    {
    x = x + 1;
    Serial.println(x);
    delay(200);
    }
    }
    The while statement is used as a loop that will execute as long as the condition in parentheses is true. In the example, the while loop statement will repeat the code in parentheses endlessly until x is less than 10.
    do...while void loop()
    {
    do
    {
    x = x + 1;
    delay(100);
    Serial.println(x);
    }
    while(x< 10);
    delay(900);
    }
    The do...while loop statement works in the same way as the while loop. However, if the expression in parentheses is true, the loop continues rather than exits the loop. In the example above, if x is greater than 10, the addition operation will continue, but with a pause of 1000 ms.
    break
    continue
    switch(x)
    {
    case 1: digitalWrite (3, HIGH );
    case 2: digitalWrite (3, LOW );
    case 3: break ;
    case 4: continue ;
    default : digitalWrite (4, HIGH );
    }
    Break is used to force exit from switch, do, for and while loops without waiting for the loop to complete.
    The continue statement skips the remaining statements in the current loop step.

    Syntax

    ;
    (semicolon)

    digitalWrite(3, HIGH);
    A semicolon is used to mark the end of a statement. Forgetting a semicolon at the end of a line results in a compilation error.
    {}
    (braces)
    void setup()
    {
    pinMode(3, INPUT);
    }
    The opening parenthesis “(” must be followed by the closing parenthesis “)”. Unmatched parentheses can lead to hidden and unintelligible errors when compiling a sketch.
    //
    (comment)
    x = 5; // comment

    Hello! I am Alikin Alexander Sergeevich, a teacher of additional education, I lead the “Robotics” and “Radio Engineering” clubs at the Center for Youth and Youth Technology in Labinsk. I would like to talk a little about a simplified method of programming Arduino using the ArduBlock program.

    I introduced this program into the educational process and am delighted with the result; it is in great demand among children, especially when writing simple programs or for creating some initial stage of complex programs. ArduBlock is a graphical programming environment, i.e. all actions are performed with drawn pictures with signed actions in Russian, which greatly simplifies the learning of the Arduino platform. Children from the 2nd grade can easily master working with Arduino thanks to this program.

    Yes, someone might say that Scratch still exists and it is also a very simple graphical environment for Arduino programming. But Scratch does not flash the Arduino, but only controls it via a USB cable. Arduino is computer dependent and cannot work autonomously. When creating your own projects, autonomy is the main thing for Arduino, especially when creating robotic devices.

    Even well-known LEGO robots, such as NXT or EV3, are no longer so interesting to our students with the advent of the ArduBlock program in Arduino programming. Arduino is also much cheaper than any LEGO construction kits, and many components can simply be taken from old household electronics. The ArduBlock program will help not only beginners, but also active users of the Arduino platform.

    So, what is ArduBlock? As I already said, this is a graphical programming environment. Almost completely translated into Russian. But the highlight of ArduBlock is not only this, but also the fact that the ArduBlock program we wrote converts into Arduino IDE code. This program is built into the Arduino IDE programming environment, i.e. it is a plugin.

    Below is an example of a blinking LED and a converted program in Arduino IDE. All work with the program is very simple and any student can understand it.

    As a result of working with the program, you can not only program Arduino, but also study commands that we do not understand in text format Arduino IDE, but if you’re too lazy to write standard commands, you can quickly use the mouse to sketch out a simple program in ArduBlok, and debug it in Arduino IDE.

    To install ArduBlok, you must first download and install the Arduino IDE from the official Arduino website and understand the settings when working with the board Arduino UNO. How to do this is described on the same website or on Amperka, or watch it on YouTube. Well, when all this is figured out, you need to download ArduBlok from the official website, here. I don’t recommend downloading the latest versions, they are very complicated for beginners, but the version from 2013-07-12 is the best, this file is the most popular there.

    Then, rename the downloaded file to ardublock-all and in the “documents” folder. We create the following folders: Arduino > tools > ArduBlockTool > tool and in the latter we throw the downloaded and renamed file. ArduBlok works on everyone operating systems, even on Linux, I checked it myself on XP, Win7, Win8, all examples for Win7. The installation of the program is the same for all systems.

    Well, to put it simply, I prepared an archive on the 7z Mail disk, unpacking which you will find 2 folders. One is already working Arduino program IDE, and in another folder the contents must be sent to the Documents folder.

    In order to work in ArduBlok, you need to run the Arduino IDE. Then we go to the Tools tab and there we find the ArduBlok item, click on it - and here it is, our goal.

    Now let's look at the program interface. As you already understand, there are no settings in it, but there are plenty of icons for programming and each of them carries a command in Arduino IDE text format. There are even more icons in new versions, so figure it out with ArduBlok latest version difficult and some of the icons are not translated into Russian.

    In the "Management" section we will find a variety of cycles.

    In the “Ports” section, we can manage the values ​​of the ports, as well as the sound emitter, servo or ultrasonic proximity sensor connected to them.

    In the “Numbers/Constants” section, we can select digital values ​​or create a variable, but you are unlikely to use what is below.

    In the “Operators” section we will find all the necessary comparison and calculation operators.

    The Utilities section mainly uses timed icons.

    "TinkerKit Bloks" is the section for purchased TinkerKit sensors. We, of course, don’t have such a set, but this does not mean that the icons are not suitable for other sets, on the contrary, it is very convenient for the guys to use icons such as turning on an LED or a button. These signs are used in almost all programs. But they have a peculiarity - when you select them, there are incorrect icons indicating ports, so you need to remove them and substitute the icon from the “numbers/constants” section at the top in the list.

    “DF Robot” - this section is used if the sensors specified in it are available, they are sometimes found. And our today's example is no exception, we have an “Adjustable IR Switch” and a “Line Sensor”. The “line sensor” is different from the one in the picture, since it is from the Amperka company. Their actions are identical, but the Ampere sensor is much better, since it has a sensitivity regulator.

    “Seedstudio Grove” - I have never used the sensors in this section, although there are only joysticks. In new versions this section has been expanded.

    AND last section This is the Linker Kit. I did not come across the sensors presented in it.

    I would like to show an example of a program on a robot moving along a strip. The robot is very simple, both to assemble and to purchase, but first things first. Let's start with its acquisition and assembly.

    Here is the set of parts itself, everything was purchased on the Amperka website.

    1. AMP-B001 Motor Shield (2 channels, 2 A) RUB 1,890
    2. AMP-B017 Troyka Shield RUB 1,690
    3. AMP-X053 Battery compartment 3×2 AA 1 60 RUR
    4. AMP-B018 Digital line sensor RUB 2,580
    5. ROB0049 MiniQ two-wheeled platform RUB 1,1890
    6. SEN0019 Infrared obstacle sensor RUB 1,390
    7. FIT0032 Mount for infrared obstacle sensor RUB 1,90
    8. A000066 Arduino Uno 1 1150 RUR

    First, let's assemble the wheeled platform and solder the wires to the motors.

    Then we will install racks for mounting the Arduino UNO board, which were taken from the old one motherboard or other similar fastenings.

    Then we attach the Arduino UNO board to these racks, but we won’t be able to fasten one bolt - the connectors are in the way. You can, of course, unsolder them, but this is at your discretion.

    Next we attach the infrared obstacle sensor to its special mount. Please note that the sensitivity regulator is located on top, this is for ease of adjustment.

    Now we install digital line sensors, here you will have to look for a couple of bolts and 4 nuts for them. We install two nuts between the platform itself and the line sensor, and fix the sensors with the rest.

    Next we install Motor Shield, or otherwise you can call it the motor driver. In our case, pay attention to the jumper. We will not be using a separate power supply for the motors, so it is installed in this position. The lower part is sealed with electrical tape to prevent accidental short circuits from the Arduino UNO USB connector, just in case.

    We install Troyka Shield on top of the Motor Shield. It is necessary for the convenience of connecting sensors. All the sensors we use are digital, so the line sensors are connected to ports 8 and 9, as they are also called pins, and the infrared obstacle sensor is connected to port 12. Be sure to note that you cannot use ports 4, 5, 6, 7 as they are used by Motor Shield to control motors. I even specially painted over these ports with a red marker so that the students could figure it out.

    If you have already noticed, I added a black bushing, just in case, so that the battery compartment we installed would not fly out. And finally, we secure the entire structure with a regular elastic band.

    There are 2 types of battery compartment connections. First connection of wires to Troyka Shield. It is also possible to solder the power plug and connect it to the Arduino board UNO.

    Our robot is ready. Before you start programming, you will need to learn how everything works, namely:
    - Motors:
    Ports 4 and 5 are used to control one motor, and 6 and 7 another;
    We regulate the rotation speed of the motors using PWM on ports 5 and 6;
    Forward or backward by sending signals to ports 4 and 7.
    - Sensors:
    We are all digital, so they give logical signals in the form of 1 or 0;
    And in order to adjust them, they have special regulators, and with the help of a suitable screwdriver they can be calibrated.

    Details can be found at Amperke. Why here? Because there is a lot of information on working with Arduino.

    Well, we probably looked at everything superficially, studied it and, of course, assembled the robot. Now it needs to be programmed, here it is - the long-awaited program!

    And the program converted to Arduino IDE:

    Void setup() ( pinMode(8 , INPUT); pinMode(12 , INPUT); pinMode(9 , INPUT); pinMode(4 , OUTPUT); pinMode(7 , OUTPUT); pinMode(5, OUTPUT); pinMode(6 , OUTPUT); ) void loop() ( if (digitalRead(12)) ( if (digitalRead(8)) ( if (digitalRead(9)) ( digitalWrite(4, HIGH); analogWrite(5, 255); analogWrite( 6, 255); digitalWrite(7, HIGH); ) else ( digitalWrite(4, HIGH); analogWrite(5, 255); analogWrite(6, 50); digitalWrite(7, LOW); ) ) else ( if (digitalRead (9)) ( digitalWrite(4, LOW); analogWrite(5, 50); analogWrite(6, 255); digitalWrite(7, HIGH); ) else ( digitalWrite(4, HIGH); analogWrite(5, 255); analogWrite(6, 255); digitalWrite(7, HIGH); ) else ( digitalWrite(4, HIGH); analogWrite(5, 0); analogWrite(6, 0); digitalWrite(7, HIGH); ) )

    In conclusion, I want to say that this program is simply a godsend for education; even for self-study, it will help you learn Arduino commands IDE. The main highlight is that there are more than 50 installation icons, it starts to “glitch”. Yes, indeed, this is the highlight, since programming only on ArduBlok all the time will not teach you programming in the Arduino IDE. The so-called “glitch” gives you the opportunity to think and try to remember commands for precise debugging of programs.

    I wish you success.

    So you have a processor. You probably understand that the processor can be somehow programmed to do what you want. In order for useful work to be done, it is necessary to (a) write useful program and (b) give it to the processor for execution.

    In general, it doesn’t matter which processor you have: the latest Intel Pentium in your laptop or a microcontroller on an Arduino board. Principles of writing a program, i.e. programming, in both cases the same. The only difference is the speed and scope of capabilities for working with other devices.

    What is a program and where to write it

    The processor, despite all the complexity of production, is essentially a rather simple and straightforward thing. He doesn't know how to think. He can only blindly, byte by byte, execute the instructions that were handed to him. A rough example of the sequence of instructions can be given:

    Instruction byteWhat does it mean for the processor
    00001001 means: take the next byte and store it in cell No. 1
    00000110 ...this is exactly the next byte that we remember in cell No. 1: the number 5
    00011001 means: subtract one from the value in cell No. 1 and leave the updated result there
    00101001 means: compare the value in cell No. 1 with zero and if it is zero, jump through as many bytes as indicated in the next byte
    00000100 ...if the result was zero, we want to jump 4 bytes to the penultimate instruction
    10000011
    01000001 ...the letter “A” corresponds exactly to this code
    00101000 means that we want to jump back as many bytes as indicated in the next byte
    00000110 ...we will jump 6 bytes back to instruction No. 3
    10000011 means that we want to display the character whose code is written in the next byte
    00100001 ...sign "!" This code exactly matches

    As a result of executing this sequence of instructions, the panicked phrase “AAAH!” will be displayed on the screen.

    Quite a lot of code for such a simple purpose! It is clear that if all programs were written like this, directly, the development of complex products would take centuries.

    Why are programming languages ​​needed?

    To simplify the task a million times, programming languages ​​were invented. There are a lot of them, and even from those that are constantly heard, you can quickly remember a dozen or two: Assembler, C, C++, C#, Java, Python, Ruby, PHP, Scala, JavaScript.

    Programs in these languages ​​are much closer to natural human language. And therefore they are easier, faster and more pleasant to write, and most importantly, they are much simpler read: to you immediately after writing, to you a year later, or to your colleague.

    The problem is that such languages ​​are not understandable to the processor and before you give it this program, you need to compile: translate from natural language into those same instructions in the form of zeros and ones. This is done by programs called compilers. Each language, unless it remains at the fantasy level, has its own compiler. For popular languages ​​there are usually several to choose from, from different manufacturers and for different platforms. Most of them are freely available on the Internet.

    So, there are programs in a language that is completely understandable to humans: they are also called “source code”, simply “code” or “source codes”. They are written in simple text files by using any text editor, even using notepad. Then they are turned into sets of zeros and ones understandable to the processor using the compiler: the compiler receives as input source code, and at the output creates binary executable file , the one understandable to the processor.

    Binary files are not readable and are generally intended only for execution by the processor. They may have different type depending on what they were received for: .exe are programs for Windows, .hex are programs for execution by a microcontroller such as Arduino, etc.

    Why are there so many programming languages ​​and what is the difference?

      Why? Because there are many people and companies on Earth, and many believed that they could do the best: more convenient, clearer, faster, slimmer.

      What is the difference: different languages ​​have a different balance of writing speed, readability and execution speed.

    Let's look at the same program, which displays a song about 99 bottles of beer on the screen. different languages programming.

    For example, the Perl language. It is written quickly; it is impossible to understand what the programmer meant; executed slowly:

    sub b( $n = 99 - @_ - $_ || No; "$n bottle" . "s" x!!-- $n . "of beer" ) ; $w = "on the wall" ; die map ( b. "$w, \n". b. ", \n Take one down, pass it around,\n ". b(0) . "$w. \n\n"} 0 .. 98

    Java language. It takes a relatively long time to write; easy to read; executes quite quickly, but takes up a lot of memory:

    class bottles ( public static void main( String args) ( String s = "s" ; for (int beers= 99 ; beers>- 1 ; ) ( System.out .print (beers + "bottle" + s + "of beer on the wall, " ) ; System.out .println (beers + "bottle" + s + "of beer, " ) ; if (beers== 0 ) ( System.out .print ( "Go to the store, buy some more,") ; System.out .println ( "99 bottles of beer on the wall.\n ") ; System.exit(0); ) else System.out .print ( "Take one down, pass it around,") ; s = (-- beers == 1) ? "" : "s" ; System.out .println (beers + "bottle" + s + " of beer on the wall.\n ") ; } } }

    Assembly language. It takes a long time to write; difficult to read; executes very quickly:

    code segment assume cs : code , ds : code org 100h start : ; Main loop mov cx, 99; bottles to start with loopstart: call printcx ; print the number mov dx , offset line1 ; print the rest of the first line mov ah, 9; MS-DOS print string routine int 21h call printcx ; print the number mov dx , offset line2_3 ; rest of the 2nd and 3rd lines mov ah, 9 int 21h dec cx; take one down call printcx ; print the number mov dx , offset line4 ; print the rest of the fourth line mov ah, 9 int 21h cmp cx, 0; Out of beer? jne loopstart ; if not, continue int 20h ; quit to MS-DOS ; subroutine to print CX register in decimal printcx: mov di , offset numbufferend ; fill the buffer in from the end mov ax, cx ; put the number in AX so we can divide it printcxloop: mov dx, 0 ; high-order word of numerator - always 0 mov bx, 10 div bx ; divide DX:AX by 10. AX=quotient, DX=remainder add dl , "0" ; convert remainder to an ASCII character mov[ds:di],dl; put it in the print buffer cmp ax, 0; Any more digits to compute? je printcxend ; if not, end dec di ; put the next digit before the current one jmp printcxloop ; loop printcxend: mov dx , di ; print, starting at the last digit computed mov ah, 9 int 21h ret; Data line1 db "bottles of beer on the wall,", 13 , 10 , "$" line2_3 db "bottles of beer," 13 , 10 , "Take one down, pass it around,", 13 , 10 , "$" line4 db "bottles of beer on the wall.", 13 , 10 , 13 , 10 , "$" numbuffer db 0 , 0 , 0 , 0 , 0 numbufferend db 0 , "$" code ends end start

    How is Arduino programmed?

    If we talk about Arduino or microcontrollers from Atmel, in what language can you write programs for them? The theoretical answer: any. But in practice, the choice is limited to the languages ​​Assembler, C and C++. This is due to the fact that, in comparison with desktop computer they have very limited resources. Kilobytes of memory, not gigabytes. Megahertz on the processor, not gigahertz. This is a price to pay for cheapness and energy efficiency.

    Therefore, we need a language that can compile and execute efficiently. That is, it is translated into those very zeros and ones from instructions as optimally as possible, without wasting precious instructions and memory. The aforementioned languages ​​have this kind of efficiency. Using them even within the narrow limits of microcontroller resources, you can write feature-rich programs that run quickly.

    Assembler, as you have seen, cannot be called the simplest and most elegant and, as a result, the flagship language for Arduino is C/C++.

    Many sources say that Arduino is programmed in Arduino language, Processing, Wiring. This is not an entirely correct statement. Arduino is programmed in C/C++, and what is called in these words is just a convenient “body kit” that allows you to solve many common problems without reinventing the wheel every time.

    Why are C and C++ mentioned in the same sentence? C++ is a superset of C. Every C program is correct program for C++, but not vice versa. You can use both. More often than not, you won't even think about what you're using when solving the current problem.

    Closer to the point: the first program

    Let's write the first program for Arduino and make the board execute it. You need to create a text file with the source code, compile it and feed the resulting binary file to the microcontroller on the board.

    Let's go in order. Let's write the source code. You can write it in notepad or any other editor. However, to make the work convenient, there are so-called development environments (IDE: Integrated Development Environment). They provide in the form of a single tool and text editor with backlighting and hints, and a compiler launched by a button, and many other joys. For Arduino, this environment is called Arduino IDE. It is freely available for download on the official website.

    Install the environment and run it. In the window that appears, you will see: most of the space is given to the text editor. The code is written into it. Code in the Arduino world is also called sketch.

    So let's write a sketch that doesn't do anything. That is, the minimum possible the right program in C++, which just wastes time.

    void setup() ( ) void loop() ( )

    Let's not focus on the meaning of the written code for now. Let's compile it. To do this, in the Arduino IDE, there is a “Verify” button on the toolbar. Click it and in a few seconds the binary file will be ready. This will be announced by the inscription “Done compiling” under the text editor.

    As a result, we have a binary file with the extension .hex, which can be executed by the microcontroller.

    Now you need to slip it into the Arduino. This process is called booting, flashing or flooding. To upload to the Arduino IDE, there is an “Upload” button on the toolbar. Connect the Arduino to your computer via a USB cable, click “Upload” and in a few moments the program will be uploaded to the Arduino. In this case, the program that was there previously will be erased.

    About successful firmware will announce the inscription “Done Uploading”.

    If you encounter an error when trying to download, make sure that:

      In the Tools → Board menu, select the port to which the Arduino is actually connected. You can plug the USB cable in and out to see which port appears and disappears: this is the Arduino.

      You have installed necessary drivers for Arduino. This is required on Windows, not required on Linux, and only required on older boards prior to Arduino Duemilanove on MacOS.

    Congratulations! You've come all the way from clean slate to a running program in Arduino. She may not do anything, but this is already a success.