Menu English Ukrainian russian Home

Free technical library for hobbyists and professionals Free technical library


ENCYCLOPEDIA OF RADIO ELECTRONICS AND ELECTRICAL ENGINEERING
Free library / Schemes of radio-electronic and electrical devices

Arduino. Digital I/O operations. Encyclopedia of radio electronics and electrical engineering

Free technical library

Encyclopedia of radio electronics and electrical engineering / Radio amateur designer

Comments on the article Comments on the article

Having loaded the Arduino IDE development environment, you can see that in the blank of the future program displayed in the window that opens, there are two functions: setup () and loop (). The setup() function starts any program. It performs it once immediately after power is applied to the board, and also each time after pressing the RESET button on the board, which sets the microcontroller to its original state. Inside this function, the operating modes of the ports are set, the serial interface and other peripheral devices are initialized, both inside the microcontroller and external ones connected to it. This function, even if it is empty, must be present in the program.

The loop() function contains an infinite loop that the microcontroller repeatedly executes, until the power is turned off. It interrogates external sensors, sends commands to actuators, performs calculations and other operations. As an example, let's take a simple program that, with a period of one second, lights up and then extinguishes the LED built into the Arduino board, marked on it with the letter L and connected to digital pin D13.

This program is one of the standard examples provided with the Arduino IDE. In table. 1 shows its text in the form in which it is attached. Note that in Arduino jargon, the source code of the program is called a "sketch" - a sketch.

Table 1

Arduino. Digital I/O Operations

Program fragments belonging to one block are limited by curly braces { and }. In what follows, we will refer to them as operator brackets. The text of the program may contain a comment explaining its essence and nuances of work. A multi-line comment is limited to combinations of characters /* (at the beginning) and */ (at the end). The characters // start a comment ending at the end of the same line. During translation (transformation of the text of the program in a programming language understandable to a person into machine code executable by the microcontroller), this part of the text is completely ignored.

The only executable line in the body of the setup() function

pinMode (13, OUTPUT);

sets pin D13 of the Arduino board to output mode.

The loop() function starts with the line

digitalwrite(13, HIGH);

It sets the output D13 high logic level. In Arduino UNO, it is equal to the supply voltage (+5 V) relative to the common wire. This will turn on the LED.

It is followed by the line

delay (1000);

It causes the executable program not to jump to the next line for the time specified in brackets in milliseconds. After a pause, the program sets the D13 output to a low logic level corresponding to the potential of the common wire, which turns off the LED. This operation is described by the line

digitalwrite(13, LOW);

Next, the program once again maintains a pause of 1 s, after which it repeats from the beginning the entire sequence of operations described in the body of the loop() function. This continues until the microcontroller is turned off.

The delay() function should be used with care. If any important event occurs during the time interval specified in it (for example, a sensor is triggered for a short time), the program will not respond to this event.

It should be remembered that the maximum current given by the Arduino pin, working as an output, is 40 mA, while the total current of all outputs should not exceed 300 mA. This is enough to power ordinary LEDs, you can also directly connect a low-voltage reed relay or a low-power vibration motor from a cell phone to the output. You won't be able to connect anything more powerful without an amplifier, and it's dangerous - you can ruin the microcontroller.

Analog inputs A0-A5 can be used as digital inputs and outputs along with D0-D13 if necessary, referring to them respectively by numbers 14 to 19.

Now let's modify the program a little. For such a simple algorithm, these modifications are not fundamental, but in more complex cases, such changes are important. First of all, let's replace the comment in English with Russian. For example, the line that turns on the LED will be commented as follows: "Turn on the LED". You should not write: "We set a high level on the D13 line", this is already clear from the text of the program.

Of course, a detailed comment on each line is usually redundant, but one should not be lazy to write it. After some time, the details of the program will be forgotten, even the author himself, only a comment will help you quickly understand its essence.

Next, we will change the program so that the LED connected not to the D13 pin, but to the D12 pin of the Arduino, blinks. Since there is no LED connected to D12 on the board, an external LED with a series resistor is required. Connect it according to the diagram shown in Fig. 1. The additional resistor is selected so that the current-cut LED is within 5 ... 10 mA. This will provide a fairly bright glow for most LEDs. The Arduino UNO board with an external LED connected is shown in fig. 2.

Arduino. Digital I/O Operations
Rice. 1. LED connection diagram

Arduino. Digital I/O Operations
Rice. 2. Arduino UNO board with external LED connected

It is advisable to make several LEDs with additional resistors. They will be useful not so much for making an automaton of lighting effects, but for quickly checking the voltage levels at the outputs of the board and monitoring their change in accordance with the program being debugged.

To control an LED connected not to D13, but to D12, in this case, it would be enough to correct all the numbers 13 by 12 in the program text. Apart from comments, the number 13 appears in the program text only three times, so it is not difficult to change it. However, as the volume of the program increases, the situation fundamentally changes. It is one thing to replace three numbers and quite another to replace several tens of identical numbers in different places of a long program. In addition, it may turn out that somewhere this number means something completely different and you do not need to change it.

To make such changes easier to make, we declare a variable at the beginning of the program and assign it a value corresponding to the number of the desired output:

int LEDPIN = 12;

In addition, wherever the output number 13 occurs, we will replace it with the name of this variable. If you now need to change the connection of the LED again, it will be enough to change just one number in the description of the LEDPIN variable.

The modified program is shown in Table. 2. It must be loaded into the microcontroller memory of the Arduino board. To do this, select "File→Load" from the main menu of the IDE. If the program typed in the editing window has not been saved to a file in advance, the IDE will ask you to specify the file name in which it will save it. After some time required by the Arduino IDE to translate the program into machine codes understandable to the microcontroller, the "Rx" and "Tx" LEDs will start flashing on the board, signaling the reception and transmission of messages through the serial interface of the microcontroller.

Table 2

Arduino. Digital I/O Operations

If everything was done correctly, a report on the correct loading will appear at the bottom of the program window. It will display information about how much of the available 32 KB of microcontroller program memory the loaded program occupied and how much RAM is required to accommodate variables. The LED connected to pin D12 will start flashing with a period of 2 s.

If you connect a line of five LEDs to the D8-D12 Arduino pins (Fig. 3) and load the program shown in Table. 3, it will alternately turn on for 500 ms each of these LEDs and the LED connected to D13, installed on the board. This program could turn out to be much longer if the task were solved "head-on", by simply repeating the required number of times in the setup() function the lines with different numerical numbers of the outputs, setting them up for output, and in the loop() function - a sequence of lines that turn on the next LED, pause and turn it off. The for loop statements helped shorten the program.

Arduino. Digital I/O Operations
Rice. 3. A line of five LEDs

Table 3

Arduino. Digital I/O Operations

The parentheses after the keyword for indicate the initial value of the loop variable - LEDPIN=8, the condition for executing the loop body - LEDPIN<14, and the operation performed with the loop variable after each execution of its body - LEDPIN++, which means that the value of the variable is incremented by one. If necessary, the parameters of the for loop can be easily changed.

The loop body in operator brackets follows the condition. In the first case (in the setup() function), it consists of a single line that will be executed six times with LEDPIN values ​​from 8 to 13. In the second case (in the loop() function), the loop statement specifies the sequence of three lines to be executed six times with the same variable values.

In addition to controlling external devices in any system, it is necessary to receive information from various sensors. Without them, even the most complex robot will be just a clockwork toy, unable to change its behavior depending on external conditions.

With a supply voltage of 5 V, and in Arduino UNO it is exactly that, the digital inputs of the microcontroller are guaranteed to be perceived as a logically high (corresponding to a logical unit) voltage of more than +3 V, and as a logically low (corresponding to a logical zero) - a voltage of less than +1,5 V. Intermediate values ​​(including when the input is not connected anywhere) give an unpredictable, depending on the instance of the microcontroller, its supply voltage, temperature and other factors, chaotically changing result. Therefore, it is desirable that the digital input always has a voltage of a known high or low logic level.

The simplest sensor is an ordinary button without fixation, connected as shown in fig. 4 circuit to one of the outer pins of the Arduino board, in this case to D7. When the SB1 button is released, the voltage level at the input of the microcontroller will be low (resistor R1 will provide it), when pressed, it will be high. If you change the button and the resistor in places (Fig. 5), then the levels will also change places. Now the resistor R1 will provide a high level when the button is released, and pressing it will set a low level.

Arduino. Digital I/O Operations
Rice. 4. Sensor connection diagram

Arduino. Digital I/O Operations
Rice. 5. Sensor connection diagram

The resistance of the resistor R1 should not be too small, since the current flowing through it when the button is pressed is consumed from the power source and reduces the efficiency of the device. In the case of power from a desktop computer or a mains power supply, this is not so important, but with the Arduino battery version, the low resistance of resistor R1 will greatly reduce the possible battery life of the device.

Please note that the microcontroller has internal resistors to perform the function of resistor R1. They are disabled by default. However, to connect, say, an internal resistor to the D2 input, it is enough to add the line to the setup () function

pinMode(2, INPUT_PULLUP);

Consider digital input using the example given in Table. 4 programs that extinguish the LED connected to pin 13 when you press the button connected to pin D7. It is based on the conditional operator

if (condition)

{

/*Actions if the condition is met*/

}

else

{

/*Actions if the condition is not met*/

}

Table 4

Arduino. Digital I/O Operations

It serves to select an action depending on whether the condition specified in it is met or not. If nothing needs to be done if the condition is not met, the else {...} fragment can be omitted. The use of conditional statements gives the program flexibility. Depending on the state of external sensors, they change the order of the program and the behavior of the device equipped with a microcontroller.

Actually checking the state of the button is performed by a logical operator

digitalRead(BUT) = HIGH

In this case, it compares the value returned by the function of reading the state of the BUT pin to which the button is connected with the logical constant HIGH, and if they are equal, it takes the value TRUE (true), otherwise - FALSE (false). Note that the equality test operation is denoted by two equal signs in a row. And one equal sign denotes the operation of assigning a value to a variable. Do not confuse them, this leads to hard-to-find bugs.

Using the example of the program just considered, it is easy to see what the inaccurate use of the delay () function leads to. If you "uncomment" (remove the two preceding solid lines) the delay( 10000) function in the penultimate line of the program, then after each execution of the body of the loop() function, the program will wait 10 seconds before continuing its work. Naturally, all button presses during this period of time will be ignored.

The Arduino's ability to communicate with a personal computer via a serial interface is very useful. It can be used not only to download the program to the microcontroller, but also for two-way exchange of information during its execution. Through this interface, Arduino can transfer the collected information to the computer for complex processing or storage and receive commands and initial data from it. Two microcontroller devices can also interact in this way. The microcontroller's serial port uses the board's digital pins D0 and D1, so when establishing and using communication through the serial port, they cannot be used for anything else.

For example, consider the program shown in Table. 5, which sends information about the state of output D12 to the computer. If the level on it is high, the program sends the symbol code H to the computer, and if it is low, the symbol code L. Any program that can work with the computer's COM port can receive this information. The Arduino IDE has a built-in serial port monitor that allows the computer to display text messages received from the Arduino board and send messages typed by the user on the computer's keyboard.

Table 5

Arduino. Digital I/O Operations

The Serial.begin(9600) line in the setup() function initializes the microcontroller's serial port and sets the baud rate to 9600 baud. You can also set other standard baud rates: 1200, 2400, 4800, 9600, 19200, 38400, 57600 or 115200 Baud. In this case, the speed set in the microcontroller must match the speed to which the COM port of the computer or other device is configured, with which information must be exchanged. The permissible speed at which reliable reception of information is ensured depends on the length of the cable connecting the Arduino to the computer. For example, using a standard USB cable 1,8 m long, the computer will receive information from the Arduino even at a speed of 115200 baud. And if you add a five-meter extension cable to this cable, the allowable speed drops to 4800 baud.

The Seri-al.print() function sends information to the serial port, where the name of the variable whose Send value is to be sent, or the character string to be transferred, is indicated in parentheses. To distinguish it from a variable name, the character string is enclosed in quotation marks. There is a modification to this Serial.println() function. It differs in that, having passed the information enclosed in brackets (if any), it supplements it with carriage return and line feed characters. Starts a new line and combination of characters in the given string.

Using the above program, it is easy to make sure that if no external signals are applied to the microcontroller output configured as an input, its state can be any and change randomly during operation. You can also determine the actual value of the voltage, which the microcontroller ceases to perceive as a low logic level and begins to perceive it as a high level.

Next, consider a program (Table 6) that turns on and off the LED on the board in accordance with commands received from the computer via the serial port. It should be borne in mind that information is transmitted over the serial port in bytes. The serial port receiver, operating independently of the microcontroller's processor, receives these bytes and stores them in its 64-byte buffer.

Table 6.

Arduino. Digital I/O Operations

In order for the program to determine whether there are received bytes in the buffer, there is a Serial.available() function that returns their number. If they are, the program using the Serial. read() reads a byte from the buffer and assigns its value (the received character code) to a C char variable. Next, the conditional statements compare the code with the patterns and, if they match, turn the LED on or off.

You can send commands using the same serial port monitor that was used to receive information. In the upper part of its window (Fig. 6) there is a line for entering the transmitted characters. After entering a symbol or their sequence from the keyboard, press the "Submit" screen button. On the Arduino board, the "Rx" LED should flash briefly, indicating that the microcontroller has received information. Of course, manual transmission of codes is an easy, but far from the best method of management. Usually, a special computer control program is written for this.

Arduino. Digital I/O Operations
Rice. 6. Program window

Thus, using the Arduino microcontroller board, you can relatively easily create a number of simple electronic devices. If we limit ourselves to digital input-output, these can be automatic lighting effects, the simplest burglar alarm, meters of various parameters with digital sensors. Moreover, it is easy to make the device interact with the computer. Naturally, the capabilities of Arduino are far from limited to those described in this article. This board can also work with analog signals, which will be discussed later.

The programs for Arduino mentioned in the article can be downloaded from ftp://ftp.radio.ru/pub/2016/08/diginout.zip.

Author: D. Lekomtsev

See other articles Section Radio amateur designer.

Read and write useful comments on this article.

<< Back

Latest news of science and technology, new electronics:

The world's tallest astronomical observatory opened 04.05.2024

Exploring space and its mysteries is a task that attracts the attention of astronomers from all over the world. In the fresh air of the high mountains, far from city light pollution, the stars and planets reveal their secrets with greater clarity. A new page is opening in the history of astronomy with the opening of the world's highest astronomical observatory - the Atacama Observatory of the University of Tokyo. The Atacama Observatory, located at an altitude of 5640 meters above sea level, opens up new opportunities for astronomers in the study of space. This site has become the highest location for a ground-based telescope, providing researchers with a unique tool for studying infrared waves in the Universe. Although the high altitude location provides clearer skies and less interference from the atmosphere, building an observatory on a high mountain poses enormous difficulties and challenges. However, despite the difficulties, the new observatory opens up broad research prospects for astronomers. ... >>

Controlling objects using air currents 04.05.2024

The development of robotics continues to open up new prospects for us in the field of automation and control of various objects. Recently, Finnish scientists presented an innovative approach to controlling humanoid robots using air currents. This method promises to revolutionize the way objects are manipulated and open new horizons in the field of robotics. The idea of ​​controlling objects using air currents is not new, but until recently, implementing such concepts remained a challenge. Finnish researchers have developed an innovative method that allows robots to manipulate objects using special air jets as "air fingers". The air flow control algorithm, developed by a team of specialists, is based on a thorough study of the movement of objects in the air flow. The air jet control system, carried out using special motors, allows you to direct objects without resorting to physical ... >>

Purebred dogs get sick no more often than purebred dogs 03.05.2024

Caring for the health of our pets is an important aspect of the life of every dog ​​owner. However, there is a common assumption that purebred dogs are more susceptible to diseases compared to mixed dogs. New research led by researchers at the Texas School of Veterinary Medicine and Biomedical Sciences brings new perspective to this question. A study conducted by the Dog Aging Project (DAP) of more than 27 companion dogs found that purebred and mixed dogs were generally equally likely to experience various diseases. Although some breeds may be more susceptible to certain diseases, the overall diagnosis rate is virtually the same between both groups. The Dog Aging Project's chief veterinarian, Dr. Keith Creevy, notes that there are several well-known diseases that are more common in certain breeds of dogs, which supports the notion that purebred dogs are more susceptible to disease. ... >>

Random news from the Archive

Levi's smart jacket 05.12.2018

Many probably had to at least once find themselves in a situation where, having arrived at work or somewhere else, they found that they had forgotten their smartphone at home. To prevent this from happening, clothing manufacturer Levi's, together with Google, has introduced a new feature for the brand's "smart" jackets, created as part of the Jacquard project. It is called Always Together, which means "Always Together" in English.

The Always Together function is automatic and involves the inclusion of an indicator light and vibration every time the sensor located on the jacket is at a certain distance from the smartphone tied to it. A notification is also sent to the smartphone, so the owner will not need to waste time searching for the device around the apartment or manually turning on the Find Your Phone mode.

The first product designed by Jacquard went on sale in September 2017, more than a year ago. This is Levi's Commuter Trucker Jacket, a $350 "smart" denim jacket aimed primarily at cyclists. Thanks to microsensors sewn into the fabric, which were developed by Google Advanced Technology and Projects (ATAP), users can, for example, control a multimedia player or a navigation application. The Jacquard project continues to be improved, and in the future the platform's capabilities will be expanded.

Other interesting news:

▪ The laser will take the missile away from the target

▪ Night vision is available to everyone

▪ The car recognizes the owner by fingerprint

▪ Solar panels for FlixBus

▪ Infineon 1EDN7511B and 1EDN8511B Single Channel MOSFET Drivers

News feed of science and technology, new electronics

 

Interesting materials of the Free Technical Library:

▪ section of the site Biographies of great scientists. Article selection

▪ article Rights - do not give, rights - take. Popular expression

▪ article Where do ants live that can count the number of steps taken? Detailed answer

▪ article Volcano Popocatepetl. Nature miracle

▪ article Contours for HF antennas. Encyclopedia of radio electronics and electrical engineering

▪ article Improvement of the detector receiver. Encyclopedia of radio electronics and electrical engineering

Leave your comment on this article:

Name:


Email (optional):


A comment:





All languages ​​of this page

Home page | Library | Articles | Website map | Site Reviews

www.diagram.com.ua

www.diagram.com.ua
2000-2024