• What can be cooked from squid: quick and tasty

    Any home developer of microelectronics, sooner or later, is faced with the need to control his own hand-made device by means of some kind of remote control, which will be convenient to switch operating modes or simply view the current state. In general, the phrase "home developer of microelectronics" 15 years ago, would have caused a terrible laugh, because at that time no one could have imagined that at home someone would tinker with miniature boards, deal with firmware, and in general. But it turned out that individual enthusiasts turned into a host of enthusiastic people, and the business itself received a massive turnover.

    But the years have passed and stubborn companies have created a real niche, a whole market in which millions of enthusiastic non-professionals are brewing, enthusiastically collecting another "device on arduinka". It is precisely such enthusiasts who pay long bucks to manufacturers of shields and sensors, and there is a need to control their smart devices with a remote control. And, oddly enough, their need was met by the most graceful of possible ways... Blynk was born.

    Blynk app

    What does Blynk give to the home automation lover? The answer to this question is twofold. On the one hand - not much at all, but on the other, a little turns into almost half the "cost" of the entire implemented project. Blynk allows you to turn an ordinary smartphone or tablet running Android or iOS into a real control panel for your own electronics. Blynk fits in very well with the eco-structure of the Arduino and appeared at the most opportune moment.

    In fact, Blynk is nothing more than an application for a mobile device that allows, in the form of graphical design, to create fully functional applications for connecting them with devices on the Arduino platform and compatible (to tell the truth, there will be much more compatible platforms soon). The main feature of Blynk, I can safely say, is the simplicity with which both the application itself is created and how the connection with the program code in the device is implemented.

    To get started, however, and to continue it, you just need to install the Blynk application on your mobile or tablet. Next, just slide your finger across the screen, place elements such as buttons, sliders, switches, light bulbs, plotters and so on, so on, so on. Each element has the ability to configure a few parameters, but the basis lies in the binding of controls or displays to the pins of a physical device. And the pins themselves can be both real, physical, and can be virtual. But I would recommend working with virtual ones, since the logic of their processing can be configured much more flexibly than with physical ones.

    On the device side, all you need to do is connect the library, set up a link between the source code and the registration code of the installed application, put an event handler in the loop, yes ... Yes, in general, that's all. If the application is tied only to physical pins, then nothing more needs to be done.

    It's just that simple, you get a convenient remote control for your device, capable of not only sending commands to it, but also displaying everything you need on your screen. The developers didn't even bother with advanced and detailed documentation. Everything is collected in the form of a single document on one page of the Blynk website. Well, well, for the simplicity of implementation to the developers, I send a full-fledged "respect"!

    Where did Blynk come from?

    Blynk was not born out of pure coincidence. I would even say that the emergence of Blynk is nothing more than an exemplary, happy case of successful crowdfunding. A certain Pasha Baidurin, I hope that he did not distort his surname, started a campaign on Kikstarter with a modest collection of only $ 10,000. As a result, the campaign gained five more dollars, which allowed it to develop to its fullest. Fundraising started in mid-January 2015 and by the end of the month had collected the required amount of funds. It is in this way that the brains win the loot, shake it on your mustache.

    In a little less than a year, and I am writing a review in December 2016, Blynk managed to grow up, acquire all the necessary attributes and, I hope, was able to overcome the growth problem and turned into a full-fledged corporation. At least now Blynk is offered not only for individuals, but also for legal entities... Monetization models for different types users differ, but more on that below.

    Business model uniqueness

    So what else is Blynk unique about other than being able to create a phone app in five minutes and link it to an Arduino in an extra five? And it is unique in the applied business model. In the world of software, the standard terms of use of products are accepted: Freeware (free), Shareware (shareware, with a trial period), Donationware (pay if you like it), paid products. Various combinations are allowed, for example, for private use the product may be free, and the corporate sector is obliged to pay for each copy. However, there are other types of licenses, for example, many OpenSource, when the product is viewed as a kind of building block of the source code available to everyone. But let's not go deeper and take a closer look at Blynk.

    Interface in the Blynk app on a smartphone

    By default, an ordinary private user who downloaded Blynk from the market is given a limited set, no, not elements, but a battery charge. One charge is spent on using interface elements to create your application. Let's say that initially you have a value of 1000 units of charge. Each button installed in the project will cost you 200 units, and something more complicated, for example, a graph builder, will be released already in 400. Thus, building your application from elements, you spend the energy allocated to you initially. Once the energy is depleted, it will no longer be possible to add new elements to the application. You either have to buy additional energy for real money, and the operation is extremely simple, like everything else in Blynk, or you can remove elements from the application. When removed, the energy spent on the installation is returned back in full.

    Thus, the developers allow a new user to evaluate the capabilities of Blynk and create at least one more or less functional application. And then - if you want to pay, if you don't want to, disassemble what you have created and reuse. The uniqueness of the situation lies in the fact that the user is offered to buy not an application, not a subscription to it, not a traffic restriction, but elements of the interface of his application! Recharging Blynk's battery is not expensive and can be classified as a micropayment. Therefore, parting with hard earned money occurs imperceptibly and painlessly.

    But still appreciate the idea. Imagine that you are using MS Word and you are invited to write texts of no more than ten pages. And to write the eleventh, you will either need to buy more virtual paper, or build brevity into a benefactor and reduce your text to a minimum. And after printing, completely erase it all. Despite the absurdity of implementing the example, everything works with Blynk. And it works great.

    For corporate users, whose work is directly related to the release of applications for commercial or near-commercial purposes, a slightly different scheme of payment for the work of developers in Blynk is offered. Corporations get a stand alone application that does not work in the Blynk sandbox, but separately. Blynk will still be there, hidden behind the facade. And you will have to pay for a subscription, during which the application will remain functional.

    Imagine you are manufacturing ultrasonic humidifiers. You have already decorated each of your models with blue LEDs and are seriously thinking how to screw the IoT there as well. Blynk provides you with almost ready-made solution... You screw something like an ESP8266 to a humidifier, and offer users to download an application. Voilà! Everything works, everyone is happy. Exactly until you decide to release a new, improved line of humidifiers, sporting not only blue, but also purple LEDs. And it is quite reasonable to think that you can no longer pay for the old application. It consumes money, and it's time for the consumer to come for a new humidifier, because you have children, they need to go to college.

    Programmable lifespan for consumer products is every manufacturer's dream. Which is very easy to solve with Blynk. As, however, everything about Blynk.

    What is in return?

    But not all individuals are willing to pay money, especially for something that can be done for free. And folk thought instantly finds its bearings, enthusiasts begin to excavate alternative options for free use of the analogue of Blynk functions. And as strange as it sounds, I am one of them.

    Web server

    The easiest way to implement remote control is to use a web server on your device. Such modern chips as EPS8266 and many others allow you to connect to IP networks, including local area networks in an apartment and even with Internet access. And the free space in the controller's memory is enough to accommodate a full-fledged server.

    Accordingly, on such a device, you can deploy a simple web server optimized for the screens of mobile devices. You can call it through a shortcut on the desktop of your smartphone. Yes, in most cases, both the device and the mobile must be within the same network, but how often does it occur to you to turn on your humidifier at home when you yourself are in the Himalayas, climbing the next summit with ropes?

    When using the option with a web server, you will need to process responses from the client, and render the controls as HTML. It may not turn out as nicely and quickly as with Blynk, but it’s completely free.

    Cayenne

    Adding items to the control panel in the Caynne (browser)

    What was done? With the help of Cayenne specialists, the CayenneWiFiClient method was overloaded, in which a constructor was added to create a Cayenne object with only the authentication ID on the Cayenne service being passed to it. In this case, you need to create an Internet connection yourself.

    You need to upgrade the standard Cayenne library and put the modified file in the directory with your sketch:

    #ifndef _CAYENNEESP8266WIFICLIENT_h #define _CAYENNEESP8266WIFICLIENT_h #include "CayenneClient.h" class CayenneWiFiClient: public CayenneClient (public: / ** * Begins Cayenne session @ param. network paramken network paramken token network param. password * / void begin (const char * token, const char * ssid, const char * pass) (Blynk.begin (token, ssid, pass, CAYENNE_DOMAIN, CAYENNE_PORT);) / * void config (const char * auth, const char * domain = CAYENNE_DOMAIN, uint16_t port = CAYENNE_PORT) (Base :: begin (auth); this-> conn.begin (domain, port);) * / void config (const char * auth) (Blynk.config (auth, CAYENNE_DOMAIN , CAYENNE_PORT);)); CayenneWiFiClient Cayenne; #endif

    And the sketch itself:

    #include #define CAYENNE_PRINT Serial // Comment this out to disable prints and save space #include "CayenneDefines.h" #include "BlynkSimpleEsp8266.h" #include "CayenneESP8266WiFiClient.h" #define // the VIRTUAL_PINPINboard D4 D4 token = "YourCayenneSecurityToke"; const char * ssid = "YourWiFiNetwork"; const char * password = "YourWiFiNetworkKeyPhrase"; void setup () (// put your setup code here, to run once: Serial.begin (115200); Serial.println ("YaHoo ..."); WiFi.mode (WIFI_STA); WiFi.begin (ssid, password ); while (WiFi.waitForConnectResult ()! = WL_CONNECTED) (Serial.println ("Connection Failed! Rebooting ..."); delay (5000); ESP.restart ();) Cayenne.config (token); pinMode ( ledPin, OUTPUT);) CAYENNE_IN (VIRTUAL_PIN) (int value = getValue.asInt (); // Get value as integer Serial.print ("Value received V1P:"); Serial.print (value); Serial.println (" "); if (value == 1) (digitalWrite (ledPin, LOW);) else (digitalWrite (ledPin, HIGH);)) void loop () (// put your main code here, to run repeatedly: Cayenne.run (); delay (100); //Serial.print (".");)

    If nothing is clear from the above, then I will try to explain. First, Cayenne relies on Blynk ... Yes, Cayenne uses Blynk, just not the application that I described a few paragraphs above, but the Blynk framework, released under the MIT license. Thus, it turns out that both the Blynk application and the Cayenne, one way or another, perform the same function. In fact, it is so.

    Complete control panel in the Cayenne viewed through a browser

    The difference between the projects is as follows: Blynk focuses on a mobile application and ease of application development, Blynk is already actively monetizing. In addition to a mobile app, the Cayenne also offers a fully functional control panel on its website. And yet it does not collect money from its users. The operating concept in the Cayenne is identical to that of the Blynk. In the application or through a web browser, the user creates a project, adds buttons, lights and other indicators that can be associated with a virtual or real pin of your specific device. In addition, the Cayenne has a trigger and event mechanism. Triggers handle events received from devices. And the event model is based on a calendar schedule.

    The communication between the device and the application is carried out in the same way as in Blynk, by adding small pieces of program code to process the business logic hardwired into your device. But initially the project was honed to apply a minimal amount of client-side programming. Anyway, everything should be picked up by the Cayenne libraries. It is for this reason that in the Cayenne you can find many boards and options for connecting to the network, including various sensors from specific manufacturers. On the one hand, diversity reduces the need for programming sketches, on the other hand, it reduces the use of universal devices.

    Cayenne dashboard interface on tablet

    It was for this reason that I had the difficulty of how to connect the Cayenne to an already connected Wi-Fi connection. And I had to explain to the developers why I needed it. It is possible that the system was conceived for the very initial level of training of terminal developers, which is indirectly indicated by the number of examples of sketches that crawl out with each action.

    A bit surprised by the builder on the website. You need to get used to its logic. First we add the device, get the identification code, then connect it on the device and try to connect to the Cayenne servers. If we succeed in the connection, it will be possible to connect widgets, buttons, displays and other visualization tools to the connected device.

    Summing up after testing the Cayenne, I can say that I could not decide whether I liked the system or not. On the one hand, yes, everything that is required of her, everything is in place. On the other hand, I constantly had the feeling that something was unfinished. It is understandable, the system is new and the work plan for the implementation of all functions is probably not yet completed. Even more worrisome is the "lure" Try it for Free, without any publication, but what will happen when the "test" period ends? At least for the moment (December 2016), the Cayenne can be used for their own purposes without any fee, to train, to create their own applications. And most importantly, there are no restrictions on the amount of energy stored in the battery.

    Virtuino

    Unlike Blynk or Cayenne, Virtuino is developed by one single person. And despite the very limited resources, the result was no worse, and maybe even better than described above. So, Virtuino is the fruit of the diligence of a Greek developer, which can be found both on a separate page (in Greek), and directly on the download page of the Virtuino application from the market. For those rushing into battle, I give a direct link to the tutorial on connecting Virtuino, since at first the procedure may not be trivial.

    Like Blynk, Virtuino only uses a mobile app to create the user interface. Like the Cayenne with Blynk, Virtuino uses in-app app technology. This means that your work remains in the Virtuino sandbox and cannot exist separately from Virtuino. But Virtuino also differs from its two competitors. Virtuino does not use a staging server.

    Virtuino app interface on tablet

    I will dwell in a little more detail on this fact, since for me it is key. Blynk and Cayenne use the server side and work only through it. You cannot access the device without an Internet connection, at least for non-Bluetooth and USB connections. And if the connection is unstable, then your sketch will slow down on network connections. For some applications, slowing down the execution of instructions can be very critical. Moreover, both Blynk and Cayenne can operate from under severe NAT, which means that your device will periodically poll, literally every cycle, a server on the Internet. If the connection is poor, the execution of the sketch may not go exactly as originally intended.

    In Virtuino, a developer can take two paths. Firstly, he can use the ThingSpeak service, as the very intermediate server. And secondly, communication between the application and the device is carried out using a web server, raised on the device itself! Yes, in this case, access from outside your local network to the device will most likely not be possible. On the other hand, very few people need it. But then there are no delays and problems with external connection. Everything is implemented transparently to the point of impossibility, which is what the IoT giants lack. When working with the Cayenne, you constantly feel that at any time a fee for using the service may be introduced, and Blynk's prices will be raised and your already paid set will be inoperable. With Virtuino, you will continue to use the application and control the device. In any case, the application does not need to be updated.

    Like the Cayenne, the Virtuino has a tough ability to connect to a Wi-Fi network using Virtuino without the ability to use an already established connection. Having two of the same approaches to implementation makes you feel sad. For some incredible reason, developers significantly limit the ability of users of their products. While with the Cayenne I was able to resolve the issue of using my own network connection, in Virtuino I failed. Even with the help of a developer, I was unable to connect my ESP8266 to the network and use Virtuino. The point is that Virtuino supports ESP8266 only as an external Wi-Fi module for Arduino, and not as an independent board. And I completely switched to ESP8266 in my devices in view of their outstanding characteristics.

    Yes, in pursuit of making the consumer's life easier, some developers drive him, the consumer, into a very narrow framework and do not allow them to go beyond them. Taking 1C as an example, we remember that the more flexible and open the platform is, the more success awaits it in the market. Where are all those "sails", "galaxies" and "abacuses"? However, I contacted the developer and found out his immediate plans. The first step will be to implement customizable buttons and indicators. This work should be completed by the time the article is published, and then it will be the turn of adding new boards to the regular library. Hopefully the library will have native support for ESP8266 for Arduino.

    In general, Virtuino made a very favorable impression on me, first of all by the fact that there is an opportunity not to use an intermediate server. But the limited resources of one person do not allow to implement all ideas at once, for example, add an English-language version of the site or create a universal version of your library, and at the same time put it on GitHub. We look forward to further development and news from Illias.

    conclusions

    I am very pleased with the fact that implementations of real convergence of mobile devices and devices from the IoT world have begun to appear. Until we have the ability to easily communicate with our devices, if possible through a single or universal interface, there will be no total IoT march across the planet. A person is such a brute who is lazy to get used to something new and the presence of a dozen different interfaces for controlling IoT devices will cause endless existential pain in the joints of the end user.

    Of course, one should not count on total unification. Remember the story of smart homes? When did the boom end? And all because of the incompatibility of systems with each other and the lack of a clear, uniform standard... A similar risk exists with the IoT. Basically, we somehow got along without smart outlets, refrigerators and washing machines, and adding new “smart” features doesn't add much value to the devices. Therefore, we will closely monitor the impending battle, it is possible that one of the above methods of communication between a person and a device will win in front of our eyes. Let's see, we'll see.

    Programming a variety of microcontrollers and microcomputers such as Arduino, Raspberry Pi and the like is one of the most interesting and relevant activities. Designing devices on these platforms has gone beyond the hobby of geeks and professional programmers: these boards are used to create robots, machine tools, quadcopters, IoT devices (smart home), servers, and even Hi-Fi audio interfaces.

    Unfortunately, the microcontroller market is highly segmented. They are programmed through various environments and interfaces. The situation is called to save the project called Blynk.

    Blynk is a cloud-based service for creating graphic control panels and is suitable for a wide range of microcomputers and microcontrollers. Where previously it was necessary to write a full-fledged I / O interface or purchase additional modules to collect information from sensors, now you can get by with a five-minute work in Blynk.

    To create your own project managed through Blynk, you need very little: install the application (versions for iOS and Android are available) or use a web form. Here you will need to register in one step - enter your email and password. Registration is needed due to the fact that Blynk is a cloud solution and without it any user can get control over the piece of hardware.

    Those interested can install the server locally. In this case, Internet access is not required.

    The application will require certain skills. First, you need to pair your computer or smartphone with the programmable board. The program supports connection to boards through a wide variety of interfaces:

    • USB (Serial),
    • Adafruit CC3000 WiFi,
    • Official Arduino WiFi Shield,
    • Official Ethernet Shield (W5100),
    • ENC28J60,
    • ESP8266 (WiFi modem),
    • SeeedStudio Ethernet Shield V2.0 (W5200),
    • RN-XV WiFly,
    • ESP8266.

    In addition to setting up the connection, you only need to correctly connect the modules of the future device. After that, in the working form of the application, you need to add the available modules (widgets), configure the necessary output addresses and specify the desired parameters (if necessary, you can write your own code). By the way, drag'n'drop is used to create a widget or program. A lot of simulators of control devices are available for control - switches, sliders, displays, for each of which you can write your own logic. There are separate forms for displaying and organizing information from the required sensors in the form of graphs.

    Thus, the platform is suitable for both beginners and more advanced users who do not want to spend time writing applications for project management: from reading data from a weather station and controlling a smart home to controlling robots.

    All the information you need to get started is posted on the official website. Blynk is, so everyone can participate in the creation of new features. At the moment, using the service is completely free, in the future the situation will change somewhat - first of all, due to the monetization of new functions. So, it is already known that access to GPIO interfaces will be purchased as an in-app purchase.

    Blynk currently works with the following boards:

    • Arduino: Uno, Nano, Mini, Pro Mini, Pro Micro, Mega, YÚN (Bridge), Due;
    • Raspberry Pi;
    • Particle (ex Spark Core);
    • ESP8266;
    • TinyDuino (CC3000);
    • Wicked WildFire (CC3000).

    This example shows how to make an LED blink using an Arduino controller.

    Required components

    • Arduino controller
    • Light-emitting diode
    • resistor 220 ohm

    Connection

    We connect a 220 Ohm resistor to output number 13 (pin 13), to the resistor, in turn, we connect the anode (usually a long leg) of the LED. We connect the cathode to ground (Grd). Then we connect the controller via a USB cable to the computer and upload the code below to the Arduino controller.

    Most Arduino boards have a built-in SMT (Surface-mount techology) LED connected to pin 13. If you run the code on these boards without connecting an external LED, you should see the onboard LED on the board blinking.

    Scheme

    Code

    In the code, we set the output mode for input / output (pin) 13 on the first line:

    pinMode (13, OUTPUT);

    In the main loop of the program, turn on the LED:

    digitalWrite (13, HIGH);

    At output 13, a voltage of 5 V appears. The LED lights up. Then we turn off the LED:

    digitalWrite (13, LOW);

    By changing the output voltage to 0 volts, we turned off the LED. In order for the human eye to have time to notice the switching of the LED, we introduce a delay using the delay () function.

    / * Turn on the LED for one second, then turn it off for one second in a loop. * / void setup () (// Initialize digital I / O in output mode. // Output 13 on most Arduino boards is connected to an LED on the board.pinMode (13, OUTPUT);) void loop () (digitalWrite (13, HIGH ); // turn on the LED delay (1000); // wait a second digitalWrite (13, LOW); // turn off the LED delay (1000); // wait a second)

    see also

    So, let's get down to mastering. The first lesson does not require any material from you and is simply intended to introduce you to the simplicity of ARDUINO. As in most programs, the familiarization starts with "Hello World!" so we will start with the simplest - blinking the LED. What you need for this: the ARDUINO board itself, a USB cable for connecting ARDUINO to a computer, ARDUINO programming shell. New skins are released, but the most stable version is 1.0.6. Download you can get it on official website... This is the version for Windows, download for Linux. You should immediately understand that to continue the study you will need a breadboard (order in China or buy in an online store), wires (you can buy there or find old system units and pull out the wires going to the front panel, before even USB on the front panel were connected by single wires and not a whole connector, they will suit you - pull out the wire, solder the pins from the connectors on the board to the other end, then put a small piece of heat shrinkable tube on the soldering site so that the wire does not break at the soldering point, heat up and you have a ready mother wire (plug with a hole) - dad (pin from the board).

    Homemade wires for ARDUINO

    Make the male-to-male wires in the same way, they will be useful for switching on the breadboard and connecting ARDUINO to the breadboard. By the way, you can, even need to, make such wires in the form of a loop - it is much more convenient to connect ARDUINO with blocks), well, the blocks with which you will work (they are also bought in China or in online stores). The choice of sensors and actuators is huge and does not limit your imagination. But at first, a thermal sensor will be enough Dallas, indicator (of course, 7-segment LEDs are also possible, but they consume a current several times greater than 1602 and this will negatively affect when powered by batteries and batteries, and they only display digital information), relay, you can always buy everything that you need. For those who are not constrained in funds, it is better to immediately buy a set. Although it is expensive, it immediately discards all problems with the acquisition of sensors and you can make devices right away. The choice will still only be yours. Okay, I started talking, closer to the topic.

    We connect ARDUINO to the computer, run the program, go to the program Service-Board-choose your board, everything-you can work!

    By the way, a Chinese clone can be assembled on a microcircuit ch340 and your computer will require a driver for the USB port. To install, download the driver, unpack it and point to the folder with the unpacked files when prompted by the driver.

    Without wasting time, we do the following: File-Examples-Basics-Blink... A new window will open


    Blink on ARDUINO

    in which you will see the program, you can immediately click on the second button in the program panel with an arrow, the program will be compiled and transferred to ARDUINO, the LED on the board will start blinking! 1 second on, 1 second off. Let's consider the program itself. First of all, you will see the comments marked with /* text */ and //text ... The first means that the text from the sign /* to sign */ is a comment and the compiler simply does not process and does not take into account this information, it is very convenient to write in such combinations the description of the program, its algorithm, authorship and much more. Sign // only comments the line. Moreover, you can write this sign both at the beginning of a line, and after any lines of the program, but in no case before lines programs - program will count the entire line as a comment.

    For example:

    digitalWrite (13, HIGH); // turn the LED on (HIGH is the voltage level)- right

    // turn the LED on (HIGH is the voltage level) digitalWrite (13, HIGH);- not right

    If you want to make a comment before the operator on one line, then use the combination /* text */ , those. the line will look like this: / * turn the LED on (HIGH is the voltage level) * / digitalWrite (13, HIGH);

    Try to comment on your actions as often as possible, the compiler will cut them out of the program and you, over time, will simply forget what and how you did.

    The next thing you will see is the following text:

    // the setup function runs once when you press reset or power the board
    void setup () (
    // initialize digital pin 13 as an output.
    pinMode (13, OUTPUT);
    }

    The comment says that the setup function is called only once when you reset or re-power ARDUINO. Those. or you press the reset button on the board itself or reconnect the power.

    Then comes the operator void setup () (….)- the beginner of the actual section of settings for this sketch (this is the name of the program for ARDUINO).

    The next comment says that we define 13 pin ARDUINO as an output. I want to remind you that the page describes the pins of the board, and so the 13th output is digital (as written in the captions to the outputs) and can take only 2 states - on (while it is supplied with voltages of about 5V), i.e. logical 1 (one), or off (no voltage) i.e. logical 0 (zero). At zero, there is still a small voltage on the pin, but they are low in relation to a logical one. In addition, an LED on the board itself is connected to pin 13 through a resistor, it is he who blinks when the program is running.

    pinMode (13, OUTPUT);- pinMode- translated as pin mode, 13- pin number, OUTPUT- output, i.e. line means that the 13th output will work as an output, OUTPUT, if you write INPUT, then it will already be a DIGITAL INPUT, i.e. you can process DIGITAL data coming into this pin.

    If you connect an LED with a series-connected 1kOhm resistor to pin 13, and the other leg to pin GND, then the LED will blink along with the LED on the board. If it does not blink for you, change the polarity of the LED.

    The following lines are the program describing actions with the port:

    // the loop function runs over and over again forever
    void loop () (
    digitalWrite (13, HIGH); // turn the LED on (HIGH is the voltage level)

    digitalWrite (13, LOW); // turn the LED off by making the voltage LOW
    delay (1000); // wait for a second


    void loop () (...)
    - the section of the program where the actions for work are described, the data in this cycle can be changed and processed in accordance with the conditions. The comment says that the next cycle will be executed again and again always

    digitalWrite (13, HIGH);// turn the LED on (HIGH is the voltage level) - digitalWrite- write DIGITAL signal, 13- pin number, HIGH- high level, i.e. logical unit (voltage about 5V), further comment that we turn on the LED with a high logic level.

    delay (1000);// wait for a second-delay, wait 1000 milliseconds or 1 second. The necessary operator, especially when processing button clicks, in this case it is used as an indication to wait 1 second after turning on pin 13.

    digitalWrite (13, LOW);// turn the LED off by making the voltage LOW- like the first line of the cycle indicates that the 13th pin needs to be switched, only now to the LOW level- low level, logical zero (voltage is about 0V).

    delay (1000);// wait for a second - again a delay of 1 sec before the cycle starts over.

    Try changing the delay values, you will see that the duration of the on and pause between flashes change.

    The program is simple, understandable the first time, but it has drawbacks: the delay operator makes ARDUINO wait until it finishes its work, i.e. at this moment, the MC does not process any data, simply speaking, it waits for the operator to execute, okay if the values ​​are low, but if you need to process the data promptly? In 1 second, the data can change more than one hundred times, and the MC does not take them into account, it waits for the program to execute. In order not to miss the incoming data, you can use the following sketch. Open the sketch: File- Examples- Digital- BlinkWithoutDelay... A window with the following content will open:

    / * Blink without Delay

    Turns on and off a light emitting diode (LED) connected to a digital
    pin, without using the delay () function. This means that other code
    can run at the same time without being interrupted by the LED code.

    The circuit:
    * LED attached from pin 13 to ground.
    * Note: on most Arduinos, there is already an LED on the board
    that’s attached to pin 13, so no hardware is needed for this example.

    created 2005
    by David A. Mellis
    modified 8 Feb 2010
    by Paul Stoffregen
    modified 11 Nov 2013
    by Scott Fitzgerald

    This example code is in the public domain.

    http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
    */

    // constants won’t change. Used here to set a pin number:
    const int ledPin = 13; // the number of the LED pin

    // Variables will change:
    int ledState = LOW; // ledState used to set the LED

    // Generally, you shuould use "unsigned long" for variables that hold time
    // The value will quickly become too large for an int to store
    unsigned long previousMillis = 0; // will store last time LED was updated

    // constants won’t change:
    const long interval = 1000; // interval at which to blink (milliseconds)

    void setup () (

    pinMode (ledPin, OUTPUT);
    }

    void loop ()
    {




    // blink the LED.

    if (currentMillis - previousMillis> = interval) (


    if (ledState == LOW)
    ledState = HIGH;
    else
    ledState = LOW;



    }
    }

    We skip all comments and go to the line:

    // constants won’t change. Used here to set a pin number:
    const int ledPin = 13;// the number of the LED pin

    The comment line says that the constants do not need to be changed, that is, change the name of the constants. But you can change the digit indicating the pin number.

    const int ledPin = 13; // the number of the LED pin- const means a constant, that is, a constant value that cannot be changed in the program, int- abbreviated from the word integer, means a data type that can take values ​​from -32768 to 32768. In addition to integer, there are 5 more types data. What is the difference? They differ in size, i.e. for example, only 256 values ​​can be written to a byte variable, the difference in size is int-2 bytes (except for ARDUINO DUE, INT takes 4 bytes in it, but takes values ​​from -2147483648 to 2147483647), byte, as it is written, is 1 byte. In large programs, memory savings are very important point and therefore try to avoid using "heavier" types wherever possible if you can get by with "light" types. For example, the byte type would be enough here. 13 fits into the range between 0 and 255, and the rest of the digital pins would also fit into this data type. ledPin is the name of the constant itself. 13- the value of the constant, from the comment above it is clear that this constant will be used to select a pin.

    // Variables will change:
    int ledState = LOW;// ledState used to set the LED

    The comment says that the variable will change in the program

    int ledState = LOW;// ledState used to set the LED - declares the ledState variable with an initial value of LOW (logical zero) and a comment that the ledState variable will be used for the LED (not our LED).

    // Generally, you shuould use "unsigned long" for variables that hold time
    // The value will quickly become too large for an int to store
    // will store last time LED was updated

    The comment says that you should use an unsigned long variable for the time, the next line warns that the value will be too large for an int variable to store. Unsigned long is used to store NUMBERS and can store values ​​from 0 to 4294967295 in 4 bytes.

    unsigned long previousMillis = 0;// will store last time LED was updated - creates a variable previousMillis of type unsigned long and assigns the value 0, it will store the time when the state of the LED was updated.

    // constants won’t change:
    const long interval = 1000;// interval at which to blink (milliseconds)

    Also a constant, of type long, is intended for storing NUMBERS, takes 4 bytes and can take values ​​from -2147483648 to 2147483647, interval is the name of the variable, 1000 is the value of the variable. The comment says that this will be the blinking interval in milliseconds.

    void setup () (
    // set the digital pin as output:
    pinMode (ledPin, OUTPUT);
    }

    The function is familiar from the previous example, only here the pin is indicated not explicitly, but through a variable ledPin, which is described here as a constant and has a value of 13. That is, it is equivalent to what if it were written pinMode (13, OUTPUT);

    Well, the actual body of the program:

    void loop ()
    {
    // here is where you’d put code that needs to be running all the time.

    // check to see if it's time to blink the LED; that is, if the
    // difference between the current time and last time you blinked
    // the LED is bigger than the interval at which you want to
    // blink the LED.

    Here comments describe how the program works. By the way, you could use the combination /*text*/ instead of writing on each line // ... It says here that when the difference between the current and the last time, when the LED blinked more than the specified interval, then you need to light the LED again.

    unsigned long currentMillis = millis ();

    A variable currentMillis of unsigned long type is declared that stores operator data millis (). millis ()- the internal MK operator indicates how many milliseconds ARDUINO has worked.

    if (currentMillis - previousMillis> = interval) (
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    We got to the calculation. Now there is a wonderful operator if condition (if) - which has been used, is used and will be used for a very long time. Let's consider it in more detail. The construction of the condition looks like this:

    if (condition == value) (

    Action if condition is met

    else (

    Action if the condition is not met

    The == sign can change to any other> signs,<,>=, <=, != (не равно). Условие как и значение может высчитываться. Если условие не выполнено то программа переходит в секцию else. Довольно часто секцию else не используют а просто пишут программу дальше. Это уже зависит от алгоритма работы программы и должно быть продумано заранее. Условий может быть сколько угодно и они могу быть вложены друг в друга, т.е. пока не выполнится одно условие- другое даже выполняться не начнет.

    So the if statement subtracts the previous value from the current milliseconds and compares it with the interval variable. If the value is less then the program exits the condition and starts over, if it is greater or equal then the value of currentMillis is assigned to the variable previousMillis and the program proceeds to the next step:

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW)
    ledState = HIGH;
    else
    ledState = LOW;

    In this section, it is found out what state of the LED, if the LED was supplied with a low level LOW, then the ledState variable is assigned the value HIGH, and vice versa (section else) if the high level was HIGH, then the variable ledState is assigned the value LOW. Note that if is used here without (). This is allowed if you need to process no more than 1 line in the execution section.

    // set the LED with the ledState of the variable:
    digitalWrite (ledPin, ledState);

    Finally, we write to the value of the ledPin variable (it was equal to 13), the value of the ledState variable. Those. this line can be written as digitalWrite (13, LOW); or digitalWrite (13, HIGH); depending on the operating time of the MK. Please note that the digitalWrite operator is used - it is he who indicates that you need to transfer the value in a logical format, i.e. zero or one. He cannot accept any more meanings. Any other ledState values ​​will automatically be set to logic 1.

    }
    }

    So the work of the second program is analyzed. What is the difference between the first and the second program if they perform the same action but the second one contains 5 times more lines? As I said, the first program just waits for the delay operator to finish its work and only then continues its work. During delay, you won't be able to process any data. The second program allows you to receive, process and send data while the LED is blinking. Just add the necessary code to the loop section and enjoy your work! My friend and I calculated that the code runs in the second case about 4 million times per second, so there are practically no delays.

    And now the most important thing. After some time, having played enough, you will say, “What's the point of blinking a light bulb ... Where can you use it? Only an indicator that the device is working ... ”You will not be entirely right. You have a tool that you can do with it - it's only your fault if you can't think of anything. It's like giving any person a full set of tools and asking them to do something, for example, give a set of carpentry tools to a man, someone will plan the same board all their lives, amazed at the cleanliness with which the plane is planing and trying to sharpen the piece of iron as sharply as possible, and someone it will make high-quality furniture at the same time. Who you will decide only for you. Also my advice, somewhere I read, I don't even remember- "DO NOT LOOK FOR PROBLEMS, LOOK FOR THEIR SOLUTION!" If you use this approach, you will have much less HOW and WHY. Well, now about the blinking LED. There are a lot of tips on using various indicators on the Internet, of course it's beautiful, it gives some importance to the author, etc. ... but it hurts the most important thing - saving pins and memory. In order to connect the 1602 indicator, you need to take 6 digital pins + 2 power wires! This is if you do not use the I2C protocol. In addition, the library on the LCD is 4KB. And no one thinks about further functionality, well, they played around with the indicator and all, too, abandoned. Surely no one asked the question that it is possible to receive all the necessary information with one LED? For example errors. You wrote a function and pass the error code into it. It's convenient - you don't have to parse the code again, just see what is wrong. Or, for example, my friend assembled a gas boiler controller on ARDUINO mini, i.e. according to the temperature in the house (taken by the Dallas sensor), the circulation pump was turned on / off. When the pump was turned off, the boiler heated up to 40 ° C and stood on the igniter, the temperature in the room dropped - the pump turned on and when the coolant cooled down, the boiler turned on itself. Very convenient and significant gas savings appeared! For just some 200-300 rubles, he saved several cubic meters of gas every day! He then kept thinking - how to track the temperature in the room without connecting any WiFi and computers, I suggested - let the LED flash as many times as the number of degrees in the room ... Of course, they laughed - you will be mistaken for 20-25 times, then I suggested - let it blink first tens of degrees and after a pause - units, for example 24 degrees, first blinked 2 times, after a pause another 4. Everything! No more indicators! And it can be applied to any field! Look for non-standard approaches and try to save energy and inputs. Even if you use I2C. Good luck to everyone in mastering MK and, in particular, ARDUINO.

    • 220 ohm resistor

    Circuit

    This example uses the built-in LED that most Arduino and Genuino boards have. This LED is connected to a digital pin and its number may vary from board type to board type. To make your life easier, we have a constant that is specified in every board descriptor file. This constant is LED_BUILTIN and allows you to control the built-in LED easily. Here is the correspondence between the constant and the digital pin.

    • D13 - 101
    • D13 - Due
    • D1 - Gemma
    • D13 - Intel Edison
    • D13 - Intel Galileo Gen2
    • D13 - Leonardo and Micro
    • D13 - LilyPad
    • D13 - LilyPad USB
    • D13 - MEGA2560
    • D13 - Mini
    • D6 - MKR1000
    • D13 - Nano
    • D13 - Pro
    • D13 - Pro Mini
    • D13 - UNO
    • D13 - Yún
    • D13 - Zero

    If you want to lit an external LED with this sketch, you need to build this circuit, where you connect one end of the resistor to the digital pin correspondent to the LED_BUILTIN constant. Connect the long leg of the LED (the positive leg, called the anode) to the other end of the resistor. Connect the short leg of the LED (the negative leg, called the cathode) to the GND. In the diagram below we show an UNO board that has D13 as the LED_BUILTIN value.

    The value of the resistor in series with the LED may be of a different value than 220 ohm; the LED will lit up also with values ​​up to 1K ohm.

    Schematic

    Code

    After you build the circuit plug your Arduino or Genuino board into your computer, start the Arduino Software (IDE) and enter the code below. You may also load it from the menu File / Examples / 01.Basics / Blink. The first thing you do is to initialize LED_BUILTIN pin as an output pin with the line

    pinMode (LED_BUILTIN, OUTPUT);

    In the main loop, you turn the LED on with the line:

    digitalWrite (LED_BUILTIN, HIGH);

    This supplies 5 volts to the LED anode. That creates a voltage difference across the pins of the LED, and lights it up. Then you turn it off with the line:

    digitalWrite (LED_BUILTIN, LOW);

    That takes the LED_BUILTIN pin back to 0 volts, and turns the LED off. In between the on and the off, you want enough time for a person to see the change, so the delay () commands tell the board to do nothing for 1000 milliseconds, or one second. When you use the delay () command, nothing else happens for that amount of time. Once you "ve understood the basic examples, check out the example to learn how to create a delay while doing other things.

    Once you "ve understood this example, check out the example to learn how read a switch connected to the board.