Encyclopedia of Fire Safety

Arduino: what can be done with it. Unusual projects on Arduino Uno Designs on Arduino

How to choose Arduino This question arises for everyone who decided to create a project using Arduino for the first time. We decided on the necessary details: sensors, sensors, modules, etc., and were faced with a considerable assortment of Arduino boards, in addition, each board also has two or three analogues. Some people think that the more expensive and more powerful the better, they purchase serious solutions, such as Arduino Due, and then they realize that not all sketches work on it, and it is difficult for them to cope with the full power of this device on their own. Others take the opposite path and face resource constraints (memory, pins, ports, clock speed, power). How to find that golden mean? Let's try to figure it out...

Pay Pros Cons

Arduino Uno

functionality like ProMini and Nano
  • The board is the most common in the Arduino family; the largest number of lessons have been created for it.
  • Thanks to the presence of a DIP panel, you can change the microcontroller
  • With the same functionality as Arduino ProMini, Nano and Micro, the board is many times larger in size

Arduino Mega 2560

  • Shields created for Arduino UNO are suitable
  • Maximum number of pins
  • Expanded capacity of all types of memory
  • Cannot be installed on Breadboard without using wires

Arduino Leonardo

functionality like MICRO

  • Shields created for Arduino UNO are suitable
  • The board is an improved version of Arduino UNO and works with most of its sketches
  • Cannot be installed on Breadboard without using wires
  • Some sketches created for Arduino Uno do not work on Leonardo, because... different microcontrollers are used

Arduino Due


  • Number of pins like Arduino Mega
  • Two analog outputs have been implemented
  • Uses a powerful 32-bit microcontroller with a clock frequency of 84 MHz
  • Cannot be installed on Breadboard without using wires
  • Largest board size in the entire Arduino family
  • Not all sketches provide such a high clock frequency
  • Not everything is shield provide for the transmission of signals with a limit voltage of 3.3V
  • Supply voltage 3.3V

Arduino ProMini 3.3V

functionality like Nano and UNO


  • The lowest clock frequency of a microcontroller, only 8 MHz
  • Supply voltage 3.3V

Arduino ProMini 5V

functionality like Nano and UNO

  • Can be used to design diagrams on Breadboard
  • The smallest board in the Arduino family
  • Supplied without soldered pin contacts, allowing surface mounting
  • Shields created for Arduino UNO are not suitable
  • There is no USB controller, which requires an external programmer

Arduino NANO V3.0

functionality like ProMini and UNO


  • Can be used to design diagrams on Breadboard
  • The board is slightly larger than the Arduino ProMini, but has a USB port and does not require the use of an external programmer
  • Shields created for Arduino UNO are not suitable
  • The introduction of a USB port with a controller led to an increase in the amount of flash memory allocated for the bootloader (compared to Arduino ProMini)

Arduino MICRO

functionality like Leonardo


  • Can be used to design diagrams on Breadboard
  • The board is slightly larger than the Arduino Nano, but has all the functionality of the Arduino Leonardo
  • It is possible to simulate various USB devices when connected to a PC (the board will be detected as a mouse, keyboard, etc.)
  • Shields created for Arduino UNO are not suitable
  • Transferring the USB controller function to the microcontroller led to an increase in the amount of flash memory allocated for the bootloader

The first question influencing the choice of Arduino- what project do you want to implement?

If you want to create a ready-made project, kindly provided by other developers, then the logical purchase would be the Arduino on which the project was originally created. It is worth noting here the fact that now, in the Russian Federation, Arduino boards are distributed under the Geduino brand . That is, as you correctly understood, Arduino Micro differs from Geduino Micro in name and logo (this is not an analogue), as written on the official website. And since the latter is cheaper, the choice is obvious.

If you haven't decided on a project, but want to purchase an Arduino for your own experiments, then an important factor is the number of different examples on the network for one or another Arduino. The undoubted leader here is Arduino UNO , this is explained by the fact that this board is the oldest in the Arduino line, but is not outdated, since it has undergone quite a few changes since its creation.

If you are planning to implement your own project, then the choice of Arduino should be approached by method of elimination. If your project has modules with pins for Arduino Uno, then exclude Arduino ProMini 3.3V, Arduino ProMini 5V, an analogue of Arduino Nano), but may have a different type of USB connector, be slightly different in size, have a different USB controller, a different type of microcontroller case, board color, etc. Here you need to understand that these boards repeat the functionality of their original (to which they are similar in name), since they use the same ATmega microcontroller of the same series. The dimensions of the board, the microcontroller housing and the type of USB port can be determined from the photo. And the presence of “CH340G” in the name means that the USB controller is not a standard FTDI chip for Arduino, but its analogue CH340G, therefore, to connect such an Arduino to a computer, you need to install a driver for the CH340G chip. These boards are suitable for those who believe that a one-time driver installation is not an inconvenience, and the reduced price is an advantage over the original name.

A series of articles and training diagrams with amateur radio experiments on Arduino for beginners. This is such an amateur radio construction toy, from which, without a soldering iron, etching of printed circuit boards and the like, any electronics kettle can assemble a full-fledged working device, suitable for both professional prototyping and amateur experiments in the study of electronics.


The Arduino board is intended primarily for teaching novice radio amateurs the basics of programming microcontrollers and creating microcontroller devices with their own hands without serious theoretical training. The Arduino development environment allows you to compile and load ready-made program code into the board memory. Moreover, loading the code is extremely simple.

Arduino where to start for a beginner

First of all, to work with the Arduino board, a novice electronics engineer needs to download the Arduino development program; it consists of a built-in text editor in which we work with program code, a message area, a text output window (console), a toolbar with buttons for frequently used commands and several menus. To download its programs and communicate, this program is connected to the Arduino board via a standard USB cable.


Code written in the Arduino environment is called sketch. It is written in a text editor that has special tools for inserting/cutting, replacing/searching text. During saving and exporting, explanations appear in the message area (see the picture in the first lesson for beginners, just below), and errors may also be displayed. The console displays Arduino messages, including full error reports and other useful information. The toolbar buttons allow you to check and record a sketch, open, create and save it, open serial bus monitoring, and much more.

So, let's move on to the first lesson of Arduino circuits for beginner electronics engineers.

For the convenience of beginners, the Arduino UNO controller already has a resistance and an LED connected to pin 13 of the connector, so we don’t need any external radio elements in the first experiment.


By loading the code, Arduino allows our program to participate in system initialization. To do this, we indicate to the microcontroller commands that it will execute at the time of initial boot and then completely forget about them (i.e., these commands will be executed by the Arduino only once at startup). And it is for this purpose that in our code we select a block in which these commands are stored. void setup(), or rather in the space inside the curly braces of this function, see the program sketch.

Don't forget the curly braces! The loss of at least one of them will make the entire sketch completely unworkable. But don’t put extra parentheses either, as this will also cause an error.

Download code:
Sketch with comments and explanations in the file 001-1_mig-led.ino

Function void loop() this is where we put the commands that will be executed as long as the Arduino is turned on. Having started execution from the first command, the Arduino will reach the very end and immediately go to the beginning to repeat the same sequence. And so on an infinite number of times, as long as the board receives power. At its core, a void loop is the main function, the entry point into Arduino.


Function delay(1000) delays program processing by 1000 milliseconds. It all goes on in an eternal cycle loop().

The main conclusion after understanding our first program on Arduino: Using the void loop and void setup functions, we pass our instructions to the microcontroller. Everything that is inside the setup block will be executed only once. The contents of the loop module will be repeated in a loop as long as the Arduino remains turned on.

In the previous program there was a second delay between turning the LED on and off. There was one big minus in the simplest code of a novice Arduino operator used above. To maintain a pause between turning on and off the LED for one second, we used the function delay() and therefore at this moment the controller is not able to execute other commands in the main function loop(). Correcting code in a function loop(), presented below solves this problem.

Instead of setting the value to HIGH and then to LOW, we will get the value of ledPin and invert it. Let’s say if it was HIGH, it will become LOW, etc.

Second Arduino code option for LED control Here:

Then you can replace the function delay(). Instead, it is better to use the function millis(). It returns the number of milliseconds that have passed since the program started. The function will overflow after approximately 50 days of running the program code.

A similar function is micros(), which returns the number of microseconds that have passed since the program code was launched. The function will return to zero after 70 minutes of program operation.

Of course, this will add a few lines of code to our sketch, but it will undoubtedly make you a more experienced programmer and increase the potential of your Arduino. To do this, you just need to learn how to use the millis function.

It should be clearly understood that the simplest delay function pauses the execution of the entire Arduino program, making it unable to perform any tasks during this period of time. Instead of pausing our entire program, we can count how much time has passed before the action completes. This, nicely, is implemented using the millis() function. To make everything easy to understand, we will consider the following option for flashing an LED without a time delay.

The beginning of this program is the same as any other standard Arduino sketch.


This example uses two Arduino digital I/O pins. The LED is connected to pin 8, which is configured as OUTPUT. A button is connected to 9 via, which is configured as INPUT. When we press the button, pin 9 is set to HIGH, and the program switches pin 8 to HIGH, thereby turning on the LED. Releasing the button resets pin 9 to LOW. The code then switches pin 8 to LOW, turning off the indicator light.

To control five LEDs we will use various manipulations with Arduino ports. To do this, we will directly write data to the Arduino ports, this will allow us to set the values ​​​​for the LEDs using just one function.

Arduino UNO has three ports: B(digital inputs/outputs from 8 to 13); C(analog inputs); D(digital inputs/outputs 0 to 7)

Each port controls three registers. The first DDR specifies whether the pin will be an input or output. Using the second PORT register, you can set pin to HIGH or LOW. Using the third, you can read information about the state of the Arduino legs, if they work as an input.

To operate the circuit, we will use port B. To do this, we will set all port pins as digital outputs. Port B has only 6 legs. The DDRB register bits must be set to "1" , if the pin will be used as an output (OUTPUT), and in "0" , if we plan to use the pin as an input (INPUT). Port bits are numbered 0 to 7, but do not always have all 8 pins

Let's say: DDRB = B00111110;// set port B pins 1 to 5 as output and 0 as input.

In our running lights circuit we use five outputs: DDRB = B00011111; // set port B pins 0 to 4 as outputs.

To write data to port B, you need to use the PORTB register. You can light the first LED using the control command: PORTB = B00000001;, first and fourth LED: PORTB = B00001001 etc.

There are two binary shift operators: left and right. The left shift operator causes all data bits to move to the left, while the right shift operator moves them to the right.

Example:

varA = 1; // 00000001
varA = 1 varA = 1 varA = 1

Now let's return to the source code of our program. We need to enter two variables: upDown will include the values ​​of where to move - up or down, and the second cylon will indicate which LEDs to light.

Structurally, such an LED has one common terminal and three terminals for each color. Below is a diagram of connecting an RGB LED to an Arduino board with a common cathode. All resistors used in the connection circuit must be of the same value from 220-270 Ohms.


For a connection with a common cathode, the connection diagram for a three-color LED will be almost the same, except that the common pin will be connected not to ground (gnd on the device), but to the +5 volt pin. Pins Red, green and blue in both cases are connected to the controller digital outputs 9, 10 and 11.

We will connect an external LED to the ninth pin of Arduino UNO through a resistance of 220 Ohms. To smoothly control the brightness of the latter, we use the function analogWrite(). It provides output of a PWM signal to the controller leg. Moreover, the team pinMode() no need to call. Because analogWrite(pin,value) includes two parameters: pin - pin number for output, value - value from 0 to 255.

Code:
/*
A tutorial example for a novice Arduino developer that reveals the capabilities of the analogWrite() command for implementing the Fade effect of an LED
*/
int brightness = 0; // LED brightness
int fadeAmount = 5; // brightness change step
unsigned long currentTime;
unsigned long loopTime;

Void setup() (
pinMode(9, OUTPUT); // set pin 9 as output
currentTime = millis();
loopTime = currentTime;
}

Void loop() (
currentTime = millis();
if(currentTime >= (loopTime + 20))(
analogWrite(9, brightness); // set the value on pin 9

Brightness = brightness + fadeAmount; // add a step for changing the brightness, which will be established in the next cycle

// if reached min. or max. values, then we go in the opposite direction (reverse):
if (brightness == 0 || brightness == 255) (
fadeAmount = -fadeAmount ;
}
loopTime = currentTime;
}
}

Working Arduino with an encoder

The encoder is designed to convert the angle of rotation into an electrical signal. From it we receive two signals (A and B), which are opposite in phase. In this tutorial, we will use the SparkFun COM-09117 encoder, which has twelve positions per revolution (each position is exactly 30°). The figure below clearly shows how output A and B depend on each other when the encoder moves clockwise or counterclockwise.

If signal A goes from a positive level to zero, we read the value of output B. If output B is in a positive state at this point in time, then the encoder moves in a clockwise direction, if B outputs a zero level, then the encoder moves in the opposite direction. By reading both outputs, we are able to calculate the direction of rotation using a microcontroller, and by counting pulses from the A output of the encoder, the angle of rotation.

If necessary, you can use frequency calculations to determine how fast the encoder rotates.

Using an encoder in our tutorial example, we will adjust the brightness of the LED using the PWM output. To read data from the encoder, we will use a method based on software timers, which we have already covered.

Considering the fact that in the fastest case, we can rotate the encoder knob 180° in 1/10 of a second, this would be 6 pulses in 1/10 of a second or 60 pulses in one second.

In reality, it is not possible to rotate faster. Since we need to track all half-cycles, the frequency should be about 120 Hertz. To be completely sure, let's take 200 Hz.

Since, in this case, we use a mechanical encoder, contact bounce is possible, and the low frequency perfectly filters out such bounce.


Using program timer signals, it is necessary to constantly compare the current value of the encoder output A with the previous value. If the state changes from positive to zero, then we poll the status of output B. Depending on the result of the status poll, we increase or decrease the LED brightness value counter. The program code with a time interval of about 5 ms (200 Hz) is presented below:

Arduino beginner code:
/*
** Encoder
** To control the brightness of the LED, an encoder from Sparkfun is used
*/

Int brightness = 120; // LED brightness, start at half
int fadeAmount = 10; // brightness change step
unsigned long currentTime;
unsigned long loopTime;
const int pin_A = 12; // pin 12
const int pin_B = 11; // pin 11
unsigned char encoder_A;
unsigned char encoder_B;
unsigned char encoder_A_prev=0;
void setup() (
// declare pin 9 to be an output:
pinMode(9, OUTPUT); // set pin 9 as output
pinMode(pin_A, INPUT);
pinMode(pin_B, INPUT);
currentTime = millis();
loopTime = currentTime;
}
void loop() (
currentTime = millis();
if(currentTime >= (loopTime + 5))( // check states every 5ms (frequency 200 Hz)
encoder_A = digitalRead(pin_A); // read the state of output A of the encoder
encoder_B = digitalRead(pin_B); // encoder output B
if((!encoder_A) && (encoder_A_prev))( // if the state changes from positive to zero
if(encoder_B) (
// output B is in a positive state, which means the rotation is clockwise
// increase the brightness of the glow, no more than 255
if(brightness + fadeAmount )
else(
// output B is in the zero state, which means the rotation is counterclockwise
// reduce the brightness, but not below zero
if(brightness - fadeAmount >= 0) brightness -= fadeAmount;
}

}
encoder_A_prev = encoder_A; // save the value of A for the next loop

AnalogWrite(9, brightness); // set the brightness to the ninth pin

LoopTime = currentTime;
}
}

In this beginner's example, we'll look at working with a piezo emitter to generate sounds. To do this, let's take a piezoelectric sensor that allows us to generate sound waves in the frequency range 20 Hz - 20 kHz.

This is an amateur radio design where LEDs are located throughout the entire volume. Using this scheme, you can generate various lighting and animation effects. Complex diagrams can even display various large words. In other words, this is an elementary surround monitor

The servo drive is the main element in the design of various radio-controlled models, and its control using a controller is simple and convenient.


The control program is simple and intuitive. It starts with connecting a file containing all the necessary commands to control the servo drive. Next, we create a servo object, for example servoMain. The next function is setup(), in which we specify that the servo is connected to the ninth pin of the controller.

Code:
/*
Arduino Servo
*/
#include
Servo servoMain; // Servo object

Void setup()
{
servoMain.attach(9); // Servo connected to pin 9
}

void loop()
{
servoMain.write(45); // Rotate servo left 45°
delay(2000); // Wait 2000 milliseconds (2 seconds)
servoMain.write(0); // Rotate servo left by 0°
delay(1000); // Pause 1 s.

delay(1500); // Wait 1.5 s.
servoMain.write(135); // Rotate servo right 135°
delay(3000); // Pause 3 s.
servoMain.write(180); // Rotate servo right 180°
delay(1000); // Wait 1 s.
servoMain.write(90); // Rotate the servo 90°. Central position
delay(5000); // Pause 5 s.
}

In the main function loop(), we give commands to the servomotor, with pauses between them.

Arduino counter circuit on a 7-segment indicator

This simple Arduino project for beginners involves creating a counter circuit using a regular 7-segment common-cathode display. The program code below allows you to start counting from 0 to 9 when you press a button.

Seven-segment indicator - is a combination of 8 LEDs (the last one is responsible for the point) with a common cathode, which can be turned on in the desired sequence so that they create numbers. It should be noted that in this circuit, see the figure below, pins 3 and 8 are allocated to the cathode.


On the right is a table of correspondence between Arduino pins and LED indicator pins.

Code for this project:

byte numbers = (
B11111100, B01100000, B11011010, B11110010, B01100110,
B10110110, B10111110, B11100000, B11111110, B11100110
};
void setup() (
for(int i = 2; i pinMode(i, OUTPUT);
}
pinMode(9, INPUT);
}
int counter = 0;
bool go_by_switch = true;
int last_input_value = LOW;
void loop() (
if(go_by_switch) (
int switch_input_value = digitalRead(9);
if(last_input_value == LOW && switch_input_value == HIGH) (

}
last_input_value = switch_input_value;
) else (
delay(500);
counter = (counter + 1) % 10;
}
writeNumber(counter);
}

Void writeNumber(int number) (
if(number 9) (
return;
}
byte mask = numbers;
byte currentPinMask = B10000000;
for(int i = 2; i if(mask & currentPinMask) digitalWrite(i,HIGH);
else digitalWrite(i,LOW);
currentPinMask = currentPinMask >> 1;
}
}

You can significantly expand the potential of Arduino boards with the help of additional modules that can be connected to the PIN pins of almost any device. Consider the most popular and interesting expansion modules, or shields as they are also called.

Delays in Arduino play a very big role. Without them, even the simplest example of Blink, which blinks an LED after a given period of time, cannot work. But most novice programmers know little about time delays and use only Arduino delay without knowing the side effects of this command. In this article, I will talk in detail about timing functions and how to use them in the Arduino IDE.

There are several different commands in Arduino that are responsible for working with time and pauses:

  • delay()
  • delayMicroseconds()
  • millis()
  • micros()

They differ in accuracy and have their own characteristics that should be taken into account when writing code.

Using the arduino delay function

Syntax

Arduino delay is the simplest command and is most often used by beginners. In essence, it is a delay that pauses the program for the number of milliseconds indicated in brackets. (There are 1000 milliseconds in one second.) The maximum value can be 4294967295 ms, which is approximately equal to 50 days. Let's look at a simple example that clearly shows how this command works.

Void setup() ( pinMode(13, OUTPUT); ) void loop() ( digitalWrite(13, HIGH); // send a high signal to pin 13 delay(10000); // pause 10000ms or 10 seconds digitalWrite13, LOW); // send a low signal to pin 13 delay(10000); // pause 10000ms or 10 seconds)

In method setup We specify that pin 13 will be used as an output. In the main part of the program, a high signal is first sent to the pin, then we make a delay of 10 seconds. During this time, the program seems to be suspended. Then a low signal is given and again there is a delay and everything starts all over again. As a result, we get that the pin is alternately supplied with either 5 V or 0.

You need to clearly understand that during a pause using delay, the program’s work is suspended, the application will not receive any data from the sensors. This is the biggest disadvantage of using the Arduino delay function. You can get around this limitation using interrupts, but we will talk about this in a separate article.

Example of delay with blinking LED

An example circuit to illustrate how the delay function works.
You can build a circuit with an LED and a resistor. Then we will have a standard example - blinking an LED. To do this, you need to connect an LED with a positive contact to the pin, which we designated as output. We connect the free leg of the LED to ground through a resistor of approximately 220 Ohms (a little more is possible). You can determine the polarity by looking at its insides. The large cup inside is connected to the minus, and the small leg to the plus. If your LED is new, then you can determine the polarity by the length of the leads: the long leg is plus, the short leg is minus.

delayMicroseconds function

This function is a complete analogue of delay, except that its units of measurement are not milliseconds, but microseconds (in 1 second there are 1,000,000 microseconds). The maximum value will be 16383, which is equal to 16 milliseconds. The resolution is 4, that is, the number will always be a multiple of four. An example snippet would look like this:

DigitalWrite(2, HIGH); // send a high signal to pin 2 delayMicroseconds(16383); // pause 16383 µs digitalWrite(2, LOW); // send a low signal to pin 2 delayMicroseconds(16383); // pause 16383 µs

The problem with delayMicroseconds is exactly the same as with delay - these functions completely “hang” the program and it literally freezes for a while. At this time, it is impossible to work with ports, read information from sensors and perform mathematical operations. This option is suitable for flashing lights, but experienced users do not use it for large projects, since such failures are not needed there. Therefore, it is much better to use the functions described below.

Millis function instead of delay

The millis() function will allow you to perform a delay without delay on the Arduino, thereby circumventing the shortcomings of the previous methods. The maximum value of the millis parameter is the same as that of the delay function (4294967295ms or 50 days).

Using millis, we do not stop the execution of the entire sketch, but simply indicate how long the Arduino should simply “bypass” the exact block of code that we want to pause. Unlike delay millis, it doesn't stop anything by itself. This command simply returns to us from the microcontroller’s built-in timer the number of milliseconds that have passed since the start. With each call to loop, we ourselves measure the time that has passed since the last call of our code and if the time difference is less than the desired pause, then we ignore the code. As soon as the difference becomes greater than the required pause, we execute the code, get the current time using the same millis and remember it - this time will be the new starting point. In the next cycle, the countdown will already be from the new point and we will again ignore the code until the new difference between millis and our previously saved value reaches the desired pause again.

Delay without delay using millis requires more code, but with its help you can blink an LED and pause a sketch without stopping the system.

Here is an example that clearly illustrates the work of the team:

Unsigned long timing; // Variable for storing the reference point void setup() ( Serial.begin(9600); ) void loop() ( /* At this point the execution of the delay() analog begins. Calculate the difference between the current moment and the previously saved reference point. If the difference is greater the desired value, then execute the code. If not, do nothing */ if (millis() - timing > 10000)( // Instead of 10000, substitute the pause value you need timing = millis(); Serial.println ("10 seconds") ; ) )

First we introduce the timing variable, which will store the number of milliseconds. By default, the value of the variable is 0. In the main part of the program, we check the condition: if the number of milliseconds from the start of the microcontroller minus the number written in the timing variable is greater than 10000, then the action of outputting a message to the port monitor is performed and the current time value is written to the variable. As a result of the program's operation, the message 10 seconds will be displayed on the port monitor every 10 seconds. This method allows you to blink the LED without delay.

Micros function instead of delay

This function can also perform a delay without using the delay command. It works exactly the same as millis, but it counts microseconds rather than milliseconds with a resolution of 4 μs. Its maximum value is 4294967295 microseconds or 70 minutes. If it overflows, the value is simply reset to 0, don't forget about it.

Resume

The Arduino platform provides us with several ways to implement a delay in our project. Using delay, you can quickly pause the execution of a sketch, but at the same time you will block the operation of the microcontroller. Using the millis command allows you to do without delay in Arduino, but this will require a little more programming. Choose the best method depending on the complexity of your project. As a rule, in simple sketches and with a delay of less than 10 seconds, delay is used. If the operating logic is more complex and a large delay is required, then it is better to use millis instead of delay.

This simulator works best on the Chrome browser
Let's take a closer look at Arduino.

Arduino is not a large computer that can be connected to external circuits. Arduino Uno uses Atmega 328P
This is the largest chip on the board. This chip executes programs that are stored in its memory. You can download the program via usb using Arduino IDE. The USB port also provides power to the arduino.

There is a separate power connector. The board has two pins labeled 5v and 3.3v, which are needed to power various devices. You will also find pins marked GND, these are the ground pins (ground is 0V). The Arduino platform also has 14 digital pins, labeled 0 to 13, which connect to external nodes and have two states, high or low (on or off). These contacts can work as outputs or as inputs, i.e. they can either transmit some data and control external devices, or receive data from devices. The next pins on the board are labeled A0-A5. These are analog inputs that can receive data from various sensors. This is especially convenient when you need to measure a certain range, such as temperature. The analog inputs have additional functions that can be enabled separately.

How to use a development board.

The breadboard is needed to temporarily connect the parts, check how the device works, before you solder everything together.
All of the following examples are assembled on a breadboard so that you can quickly make changes to the circuit and reuse parts without bothering with soldering.

The breadboard has rows of holes into which you can insert parts and wires. Some of these holes are electrically connected to each other.

The two top and bottom rows are connected in rows along the entire board. These rows are used to supply power to the circuit. It could be 5V or 3.3V, but either way, the first thing you need to do is connect 5V and GND to the breadboard as shown in the picture. Sometimes these row connections may be broken in the middle of the board, then if you need to, you can connect them as shown in the picture.








The remaining holes, located in the middle of the board, are grouped into groups of five holes. They are used to connect circuit parts.


The first thing we will connect to our microcontroller is an LED. The electrical connection diagram is shown in the picture.

Why is a resistor needed in a circuit? In this case, it limits the current that passes through the LED. Each LED is designed for a certain current, and if this current is higher, the LED will fail. You can find out what value the resistor should be using Ohm's law. For those who don’t know or have forgotten, Ohm’s law says that there is a linear relationship between current and voltage. That is, the more voltage we apply to the resistor, the more current will flow through it.
V=I*R
Where V- voltage across the resistor
I- current through the resistor
R- resistance that needs to be found.
First, we must find out the voltage across the resistor. Most 3mm or 5mm LEDs you will use have an operating voltage of 3V. This means that we need to extinguish 5-3 = 2V at the resistor.

We will then calculate the current passing through the resistor.
Most 3mm and 5mm LEDs glow at full brightness at 20mA. A current greater than this can disable them, while a current of lesser intensity will reduce their brightness without causing any harm.

So, we want to connect the LED to the 5V circuit so that it carries a current of 20mA. Since all the parts are included in one circuit, the resistor will also have a current of 20mA.
We get
2V = 20 mA * R
2V = 0.02A * R
R = 100 Ohm

100 Ohms is the minimum resistance, it is better to use a little more, because LEDs have some variation in characteristics.
In this example, a 220 ohm resistor is used. Only because the author has a lot of them: wink: .

Insert the LED into the holes in the middle of the board so that its long lead is connected to one of the resistor leads. Connect the second end of the resistor to 5V, and connect the second lead of the LED to GND. The LED should light up.

Please note that there is a difference in how you connect the LED. Current flows from the longer terminal to the shorter one. In the diagram you can imagine that the current flows in the direction where the triangle is directed. Try turning the LED upside down and you will see that it will not light up.

But how you connect the resistor makes no difference at all. You can turn it over or try connecting it to a different pin of the LED, this will not affect the operation of the circuit. It will still limit the current through the LED.

Anatomy of Arduino Sketch.

Programs for Arduino are called sketch. They consist of two main functions. Function setup and function loop
Inside this function you will set all the basic settings. Which pins will work as input or output, which libraries to connect, initialize variables. Function Setup() runs only once during the sketch, when program execution starts.
this is the main function that is executed after setup(). In fact, it is the program itself. This function will run indefinitely until you turn off the power.

Arduino flashing LED



In this example, we will connect an LED circuit to one of the Arduino's digital pins and turn it on and off using a program, and you will also learn several useful functions.

This function is used in setup() part of the program and serves to initialize the pins that you will use as input (INPUT) or exit (OUTPUT). You will not be able to read or write data from the pin until you set it to respectively pinMode. This function has two arguments: pinNumber is the pin number you will use.

Mode-sets how the pin will work. At the entrance (INPUT) or exit (OUTPUT). To light the LED we must give a signal FROM Arduino. To do this, we configure the output pin.
- this function is used to set the state (state) pina (pinNumber). There are two main states (actually 3 of them), one is HIGH, there will be 5V on the pin, that’s something else Low and the pin will be 0v. This means that in order to light the LED we need to set the pin connected to the LED to a high level HIGH.

Delay. Serves to delay the operation of the program for a period specified in msec.
Below is the code that makes the LED blink.
//LED Blink int ledPin = 7;//Arduino pin to which the LED is connected void setup() ( pinMode(ledPin, OUTPUT);// setting the pin as OUTPUT) void loop() ( digitalWrite(ledPin, HIGH);// turn on the LED delay(1000);//delay 1000 ms (1 sec) digitalWrite(ledPin, LOW);//Turn off the LED delay(1000);//wait 1 sec)

A few clarifications on the code.
Lines that start with "//" are comments and are ignored by Arduino.
All commands end with a semicolon; if you forget them, you will receive an error message.

ledPin is a variable. Variables are used in programs to store values. In this example, the variable ledPin the value is assigned to 7, this is the Arduino pin number. When the Arduino program encounters a line with a variable ledPin, it will use the value we specified earlier.
So record pinMode(ledPin, OUTPUT) similar to recording pinMode(7, OUTPUT).
But in the first case, you just need to change the variable and it will change in each line where it is used, and in the second case, in order to change the variable, you will have to make changes manually in each command.

The first line indicates the type of the variable. When programming Arduino, it is important to always declare the type of variables. For now it is enough for you to know that INT announces negative and positive numbers.
Below is a simulation of the sketch. Click start to see the circuit in action.

As expected, the LED goes out and comes back on after one second. Try changing the delay to see how it works.

Control of multiple LEDs.

In this example, you will learn how to control multiple LEDs. To do this, install 3 more LEDs on the board and connect them to resistors and Arduino pins as shown below.

In order to turn the LEDs on and off one by one, you need to write a program similar to this:
//Multi LED Blink int led1Pin = 4; int led2Pin = 5; int led3Pin = 6; int led4Pin = 7; void setup() ( //set pins as OUTPUT pinMode(led1Pin, OUTPUT); pinMode(led2Pin, OUTPUT); pinMode(led3Pin, OUTPUT); pinMode(led4Pin, OUTPUT); ) void loop() ( digitalWrite(led1Pin, HIGH );//turn on the LED delay(1000);//delay 1 sec digitalWrite(led1Pin, LOW);//turn off the LED delay(1000);//delay 1 sec //do the same for the other 3 LEDs digitalWrite(led2Pin , HIGH);//light the LED delay(1000);//delay 1 sec digitalWrite(led2Pin, LOW);//extinguish the LED delay(1000);//delay 1 sec digitalWrite(led3Pin, HIGH);//light the LED delay(1000);// delay 1 sec digitalWrite(led3Pin, LOW);//extinguish the LED delay(1000);//delay 1 sec digitalWrite(led4Pin, HIGH);//turn on the LED delay(1000);// delay 1 sec digitalWrite(led4Pin, LOW);//extinguish the LED delay(1000);//delay 1 sec)

This program will work great, but it is not the most rational solution. The code needs to be changed. In order for the program to work over and over again, we will use a construction called .
Loops are useful when you need to repeat the same action several times. In the code above we repeat the lines

DigitalWrite(led4Pin, HIGH); delay(1000); digitalWrite(led4Pin, LOW); delay(1000);
full sketch code in attachment (downloads: 1260)

LED brightness adjustment

Sometimes you will need to change the brightness of the LEDs in the program. This can be done using the command analogWrite() . This command turns the LED on and off so quickly that the eye cannot see the flickering. If the LED is turned on half the time and off half the time, it will visually appear that it is glowing at half its brightness. This is called pulse width modulation (PWM or PWM in English). Shim is used quite often, since it can be used to control an “analog” component using a digital code. Not all Arduino pins are suitable for these purposes. Only those conclusions near which such a designation is drawn " ~ ". You will see it next to pins 3,5,6,9,10,11.
Connect one of your LEDs to one of the PWM pins (for the author this is pin 9). Now run the LED flashing sketch, but first change the command digitalWrite() on analogWrite(). analogWrite() has two arguments: the first is the pin number, and the second is the PWM value (0-255), in relation to LEDs this will be their brightness, and for electric motors the rotation speed. Below is an example code for different LED brightnesses.
//Change the brightness of the LED int ledPin = 9;//an LED is connected to this pin void setup() ( pinMode(ledPin, OUTPUT);// initializing the pin to the output ) void loop() ( analogWrite(ledPin, 255);// full brightness (255/255 = 1) delay(1000);//pause 1 sec digitalWrite(ledPin, LOW);//turn off LED delay(1000);//pause 1 sec analogWrite(ledPin, 191);//brightness by 3/4 (191/255 ~= 0.75) delay(1000);//pause 1 sec digitalWrite(ledPin, LOW);//turn off the LED delay(1000);//pause 1 sec analogWrite(ledPin, 127); //half brightness (127/255 ~= 0.5) delay(1000);//pause 1 sec digitalWrite(ledPin, LOW);//turn off LED delay(1000);//pause 1 sec analogWrite(ledPin, 63); //quarter brightness (63/255 ~= 0.25) delay(1000);//pause 1 sec digitalWrite(ledPin, LOW);//turn off the LED delay(1000);//pause 1 sec)

Try changing the PWM value in the command analogWrite() to see how this affects brightness.
Next, you will learn how to adjust the brightness smoothly from full to zero. You can, of course, copy a piece of code 255 times
analogWrite(ledPin, brightness); delay(5);//short delay brightness = brightness + 1;
But, you understand, this will not be practical. The best way to do this is to use the FOR loop we used earlier.
The following example uses two loops, one to decrease the brightness from 255 to 0
for (int brightness=0;brightness=0;brightness--)( analogWrite(ledPin,brightness); delay(5); )
delay(5) used to slow down the fade-in and fade-out speed 5*256=1280ms=1.28sec)
The first line uses " brightness-" to make the brightness value decrease by 1 each time the loop is repeated. Note that the loop will run until brightness >=0.Replacing the sign > on the sign >= we included 0 in the brightness range. This sketch is modeled below. //smoothly change the brightness int ledPin = 9;//an LED is connected to this pin void setup() ( pinMode(ledPin, OUTPUT);// initialization of the output pin) void loop() ( //smoothly increase the brightness (0 to 255 ) for (int brightness=0;brightness=0;brightness--)( analogWrite(ledPin,brightness); delay(5); ) delay(1000);//wait 1 sec //smoothly reduce brightness (255 to 0) for (int brightness=255;brightness>=0;brightness--)( analogWrite(ledPin,brightness); delay(5); ) delay(1000);//wait 1 sec ) )
It's not very visible, but the idea is clear.

RGB LED and Arduino

An RGB LED is actually three different colored LEDs in one package.

By switching on different LEDs with different brightnesses, you can combine them to create different colors. For Arduino, where the number of brightness levels is 256, you will get 256^3=16581375 possible colors. In reality, of course, there will be fewer of them.
The LED we will use is the common cathode. Those. all three LEDs are structurally connected by cathodes to one terminal. We will connect this pin to the GND pin. The remaining pins, through limiting resistors, must be connected to the PWM pins. The author used pins 9-11. This way it will be possible to control each LED separately. The first sketch shows how to turn on each LED individually.



//RGB LED - test //pin connections int red = 9; int green = 10; int blue = 11; void setup())( pinMode(red, OUTPUT); pinMode(blue, OUTPUT); pinMode(green, OUTPUT); ) void loop())( //turn on/off the red LED digitalWrite(red, HIGH); delay(500) ; digitalWrite(red, LOW); //turn on/off the green LED digitalWrite(green, HIGH); digitalWrite(green, LOW); //turn on/off the blue one. LED digitalWrite(blue, HIGH); digitalWrite(blue, LOW);

The following example uses the commands analogWrite() and to get different random brightness values ​​for the LEDs. You will see different colors changing randomly.
//RGB LED - random colors //pin connections int red = 9; int green = 10; int blue = 11; void setup())( pinMode(red, OUTPUT); pinMode(blue, OUTPUT); pinMode(green, OUTPUT); ) void loop())( //pick a random color analogWrite(red, random(256)); analogWrite( blue, random(256)); analogWrite(green, random(256)); delay(1000); //wait one second )

Random(256)-returns a random number in the range from 0 to 255.
In the attached file is a sketch that will demonstrate smooth color transitions from red to green, then to blue, red, green, etc. (downloads: 348)
The example sketch works, but there is a lot of duplicate code. You can simplify the code by writing your own helper function that will smoothly change from one color to another.
Here's what it will look like: (downloads: 385)
Let's look at the function definition piece by piece. The function is called fader and has two arguments. Each argument is separated by a comma and has a type declared on the first line of the function definition: void fader(int color1, int color2). You see that both arguments are declared as int, and they are given names color1 And color2 as condition variables to define a function. Void means that the function does not return any values, it simply executes commands. If you had to write a function that returned the result of multiplication, it would look like this:
int multiplier(int number1, int number2)( int product = number1*number2; return product; )
Notice how we declared Type int as a return type instead
void.
Inside the function are the commands that you have already used in the previous sketch, only the pin numbers have been replaced with color1 And color2. The function is called fader, its arguments are calculated as color1 = red And color2 = green. The archive contains a complete sketch using functions (downloads: 288)

Button

The next sketch will use a button with normally open contacts, without locking.


This means that while the button is not pressed, no current flows through it, and after being released, the button returns to its original position.
In addition to the button, the circuit uses a resistor. In this case, it does not limit the current, but “pulls” the button to 0V (GND). Those. Until the button is pressed, the Arduino pin it is connected to will go low. The resistor used in the circuit is 10 kOhm.


//determine when the button is pressed int buttonPin = 7; void setup())( pinMode(buttonPin, INPUT);//initialize the pin to the input Serial.begin(9600);//initialize the serial port) void loop())( if (digitalRead(buttonPin)==HIGH)(//if the button is pressed Serial.println("pressed"); // display the inscription "pressed" ) else ( Serial.println("unpressed");// otherwise "unpressed" ) )
There are several new commands in this sketch.
-This command takes the High and Low values ​​of the output we are testing. This output must first be configured as an input in setup().
; //where buttonPin is the pin number where the button is connected.
The serial port allows the Arduino to send messages to the computer while the controller itself is executing the program. This is useful for debugging a program, sending messages to other devices or applications. To enable data transfer via a serial port (also called UART or USART), you need to initialize it in setup()

Serial.begin() has only one argument - this is the data transfer speed between the Arduino and the computer.
The sketch uses a command to display a message on the screen in the Arduino IDE (Tools >> Serial Monitor).
- the design allows you to control the progress of program execution by combining several checks in one place.
If digitalRead returns HIGH, then the word "pressed" is displayed on the monitor. Else (otherwise) the word “released” is displayed on the monitor. Now you can try turning the LED on and off by pressing a button.
//button press detection with LED output int buttonPin = 7; int ledPin = 8; void setup())( pinMode(buttonPin, INPUT);//this time we will set button pin as INPUT pinMode(ledPin, OUTPUT); Serial.begin(9600); ) void loop())( if (digitalRead(buttonPin)= =HIGH)( digitalWrite(ledPin,HIGH); Serial.println("pressed"); ) else ( digitalWrite(ledPin,LOW); Serial.println("unpressed"); ) )

Analog input.

analogRead allows you to read data from one of the analog pins of the Arduino and displays a value in the range from 0 (0V) to 1023 (5V). If the voltage at the analog input is 2.5V, then 2.5 / 5 * 1023 = 512 will be printed
analogRead has only one argument - This is the number of the analog input (A0-A5). The following sketch shows the code for reading the voltage from the potentiometer. To do this, connect a variable resistor, the outer terminals to the 5V and GND pins, and the middle terminal to the A0 input.

Run the following code and see in the serial monitor how the values ​​change depending on the rotation of the resistor knob.
//analog input int potPin = A0;//the central pin of the potentiometer is connected to this pin void setup())( //analog pin is included as an input by default, so initialization is not needed Serial.begin(9600); ) void loop())( int potVal = analogRead(potPin);//potVal is a number between 0 and 1023 Serial.println(potVal)
The following sketch combines the button click sketch and the LED brightness control sketch. The LED will turn on from the button, and the brightness will be controlled by a potentiometer.
//button press detection with LED output and variable intensity int buttonPin = 7; int ledPin = 9; int potPin = A0; void setup())( pinMode(buttonPin, INPUT); pinMode(ledPin, OUTPUT); Serial.begin(9600); ) void loop())( if (digitalRead(buttonPin)==HIGH)(//if button pressed int analogVal = analogRead(potPin); int scaledVal = map(analogVal, 0, 1023, 0, 255); analogWrite(ledPin, scaledVal);//turn on led with intensity set by pot Serial.println("pressed"); ( digitalWrite(ledPin, LOW);//turn off if button is not pressed Serial.println("unpressed"); ) )

Delivery of new homemade products to the post office

Receive a selection of new homemade products by email. No spam, only useful ideas!

This is certainly a great starting solution, but how far can you go with Arduino? Well, quite far, but up to a certain limit, because (as in life in general) you always have to choose between simplicity and performance. This is probably why we are seeing the emergence of high-performance Arduino clones, such as on the company’s family of microcontrollers or Netduino on ARM microcontrollers. This alternative can save the developer in many cases with performance gains, but ultimately there are still hidden functions and libraries that use microcontroller resources and users will be forced to learn the microcontroller hardware.

The author personally decided to abandon Arduino completely after several months of study. In fact, according to the author, the Arduino platform itself pushed him to take this step. Below are the reasons, but first let's look at the benefits of Arduino.

Pros of Arduino (What's Great):

  • The Arduino IDE is based on the AVRGCC C compiler. Learning Arduino will ultimately help in learning C++. If you don't like specific high-level Arduino commands or libraries, you can replace them with C++ equivalents (as it turns out, not always);
  • Power supply, programming and communication with the Arduino platform is carried out using a single USB cable (or a cable with an adapter on a specialized chip for some clones);
  • With built-in libraries, you can implement some simple (and slow) project in minutes, without having to think about how these libraries are implemented and how they work. It is slow to read buttons, display data on the LCD display or send it via a serial interface, and work with electric motors;
  • Serial and SPI communication is excellent and standard.

Cons of Arduino (What's terrible):

  • Arduino IDE is the worst and most unusable code editor since Notepad. One day you'll switch to a decent external editor, but you'll still have to leave the Arduino IDE open to program the device;
  • Arduino bootloader. In order to complete any Arduino device, you will have to manually program the bootloader into each bare ATmega microcontroller. This reduces the available program Flash memory by 2 KB;
  • Just a few options: if you use official Arduino boards, you will only be able to choose from options with 30 KB or 254 KB of built-in program memory. What happens if your code takes up, say, 42 KB? The only choice is to use a Sanguino clone, which is not fully compatible with Arduino;
  • There's no easy way to change the clock speed, is there? A microcontroller model with a 3.3 V power supply and a clock frequency of 8 MHz can safely operate at a frequency of 12 MHz;
  • The digitalWrite() function executes in 56 cycles (although the author obtained a result of 400 cycles). At least it's easy to figure this out and move on to using direct port access (the second item to change, after the Arduino IDE). Generally, Arduino is not very convenient for writing efficient code;
  • You cannot (at least not easily) disable the default serial communication library to use TX and RX interrupts, whether it was running or not;
  • The timer overflow interrupt service routine runs every 16,000 cycles in the background. This is done to allow the millis() and micros() functions to work even when they are not in use;
  • An empty Arduino project for the Arduino UNO platform takes 466 Bytes and 666 Bytes for the Arduino Mega2560. The additional expenditure of resources does not suit many people, including the author of the article. It's also annoying to see project compilation errors associated with the changes described above;
  • Last but not least, the Arduino development environment undoubtedly “hides” important aspects of the microcontroller architecture: registers, interrupts and timers. Their knowledge is simply necessary.

Difficulties when using AVRGCC:

  • Having to rewrite some things in C++, the most important of which is serial communication (arguably the best part about Arduino). Luckily, there are many practical tips and guides available for this task. Other protocols are much easier to write, such as SPI;
  • You need to research which libraries include non-compile commands and include those libraries in your source code file. The most common are: avr/io.h, avr/interrupt.h, util/delay.h, stdio.h and string.h;
  • The types of byte and boolean variables should be uint8_t and bool, byte numbers such as B00010001 should be of the form 0b00010001, and so on. You will find all the other changes, there are very few of them;
  • You need more knowledge and, most importantly, not to give up.

Benefits of using AVRGCC:

  • Need a different processor to increase program memory or performance? You can use it (for example, from the same megaAVR series), and you only have to recompile the project. You will need to change some registers and interrupt names, makefile and Fuse bits;
  • Need a different clock speed? Use a different crystal, or you can use the microcontroller's built-in oscillator, just by changing the Fuse bits and makefile;
  • You can use a decent (Notepad++) or powerful (Atmel Studio 6) integrated code development environment;
  • You get full control over your code. What you wrote is being implemented. Nothing is hidden, nothing happens without your consent. You write more efficient and faster code. You will learn more.

Like Arduino, AVRGCC has a large number of tools, ready-made projects, libraries and educational materials. The choice is up to the users.

Related publications