Declarations in arduino


Разбиение на сегменты кода функциями позволяет создавать части кода, которые выполняют определенные задания. После выполнения происходит возврат в место, откуда была вызвана функция. Причиной создания функции является необходимость выполнять одинаковое действие несколько раз.

Для программистов, работающих с BASIC, функции в Arduino позволяют использовать подпрограммы (GOSUB в BASIC).

Разделения кода на функции имеет ряд преимуществ:

  • Функции позволяют организовать программу. Очень часто помогают заранее составить концепцию программы.
  • Функции кодируют одно действие в одном месте программы. Далее необходимо только отладить код функции.
  • Функции сокращают шансы на появление ошибки при необходимости изменения кода.
  • Функции сокращают текст скетчей и делают его компактным, т.к. некоторые секции используются много раз.
  • Функции облегчают использование кода в других программах делая его модульным. В этом случае функции обладают еще одним небольшим преимуществом, делая код программы легким для чтения.

Существуют две обязательные функции в скетчах Arduino setup() и loop(). Другие функции должны создаваться за скобками этих функций. В следующем примере будет создана простая функция умножения двух чисел.


Для вызова функции умножения ей передаются параметры данных:

Созданную функцию необходимо задекларировать вне скобок любой другой функции, таким образом «myMultiplyFunction()» может стоять выше или ниже функции «loop()».

Весь скетч будет выглядеть следующим образом:

Следующая функция будет считывать данные с датчика функцией analogRead() и затем рассчитывать среднее арифметическое. Затем созданная функция будет масштабировать данные по 8 битам (0-255) и инвертировать их. // датчик подключен к выводу 0

Вызов функции осуществляется присвоением ее переменной.


Using Variables in Sketches

LAST REVISION: 10/05/2022, 01:00 PM

A variable is a place to store a piece of data. It has a name, a value, and a type. For example, this statement (called a declaration):

creates a variable whose name is , whose value is , and whose type is . Later on in the program, you can refer to this variable by its name, at which point its value will be looked up and used. For example, in this statement:

it is the value of pin (13) that will be passed to the pinMode() function. In this case, you don’t actually need to use a variable, this statement would work just as well:

The advantage of a variable in this case is that you only need to specify the actual number of the pin once, but you can use it lots of times. So if you later decide to change from pin 13 to pin 12, you only need to change one spot in the code. Also, you can use a descriptive name to make the significance of the variable clear (e.g. a program controlling an RGB LED might have variables called redPin, greenPin, and bluePin).

A variable has other advantages over a value like a number. Most importantly, you can change the value of a variable using an assignment (indicated by an equals sign). For example:

will change the value of the variable to 12. Notice that we don’t specify the type of the variable: it’s not changed by the assignment. That is, the name of the variable is permanently associated with a type; only its value changes. [1] Note that you have to declare a variable before you can assign a value to it. If you include the preceding statement in a program without the first statement above, you’ll get a message like: «error: pin was not declared in this scope».

When you assign one variable to another, you’re making a copy of its value and storing that copy in the location in memory associated with the other variable. Changing one has no effect on the other. For example, after:

only pin has the value 12; pin2 is still 13.

Now what, you might be wondering, did the word «scope» in that error message above mean? It refers to the part of your program in which the variable can be used. This is determined by where you declare it. For example, if you want to be able to use a variable anywhere in your program, you can declare at the top of your code. This is called a global variable; here’s an example:

As you can see, is used in both the setup() and loop() functions. Both functions are referring to the same variable, so that changing it one will affect the value it has in the other, as in:

Here, the digitalWrite() function called from loop() will be passed a value of 12, since that’s the value that was assigned to the variable in the setup() function.

If you only need to use a variable in a single function, you can declare it there, in which case its scope will be limited to that function. For example:

In this case, the variable pin can only be used inside the setup() function. If you try to do something like this:

you’ll get the same message as before: «error: ‘pin’ was not declared in this scope». That is, even though you’ve declared pin somewhere in your program, you’re trying to use it somewhere outside its scope.

Why, you might be wondering, wouldn’t you make all your variables global? After all, if I don’t know where I might need a variable, why should I limit its scope to just one function? The answer is that it can make it easier to figure out what happens to it. If a variable is global, its value could be changed anywhere in the code, meaning that you need to understand the whole program to know what will happen to the variable. For example, if your variable has a value you didn’t expect, it can be much easier to figure out where the value came from if the variable has a limited scope.

[block scope][size of variables]

[1] In some languages, like Python, types are associated with values, not variable names, and you can assign values of any type to a variable. This is referred to as dynamic typing.


Using Functions in a Sketch

LAST REVISION: 10/05/2022, 01:00 PM

Segmenting code into functions allows a programmer to create modular pieces of code that perform a defined task and then return to the area of code from which the function was «called». The typical case for creating a function is when one needs to perform the same action multiple times in a program.

For programmers accustomed to using BASIC, functions in Arduino provide (and extend) the utility of using subroutines (GOSUB in BASIC).

Standardizing code fragments into functions has several advantages:

Functions help the programmer stay organized. Often this helps to conceptualize the program.

Functions codify one action in one place so that the function only has to be thought out and debugged once.

This also reduces chances for errors in modification, if the code needs to be changed.

Functions make the whole sketch smaller and more compact because sections of code are reused many times. They make it easier to reuse code in other programs by making it more modular, and as a nice side effect, using functions also often makes the code more readable. There are two required functions in an Arduino sketch, setup() and loop(). Other functions must be created outside the brackets of those two functions. As an example, we will create a simple function to multiply two numbers.


To «call» our simple multiply function, we pass it parameters of the datatype that it is expecting:

Our function needs to be declared outside any other function, so «myMultiplyFunction()» can go either above or below the «loop()» function.

The entire sketch would then look like this:

Another example

This function will read a sensor five times with analogRead() and calculate the average of five readings. It then scales the data to 8 bits (0-255), and inverts it, returning the inverted result.

To call our function we just assign it to a variable.

As you can see, even if a function does not have parameters and no returns is expected «(» and «)» brackets plus «;» must be given.


Everything You Need to Know About Arduino Code

Since the launch of the Arduino open-source platform, the brand has established themselves at the center of an expansive open-source community. The Arduino ecosystem is comprised of a diverse combination of hardware and software. The versatility of Arduino and its simple interface makes it a leading choice for a wide range of users around the world from hobbyists, designers, and artists to product prototypes.

The Arduino board is connected to a computer via USB, where it connects with the Arduino development environment (IDE). The user writes the Arduino code in the IDE, then uploads it to the microcontroller which executes the code, interacting with inputs and outputs such as sensors, motors, and lights.

Both beginners and experts have access to a wealth of free resources and materials to support them. Users can look up information on how to set up their board or even how to code on Arduino. The open source behind Arduino has made it particularly friendly to new and experienced users. There are thousands of Arduino code examples available online. In this post, we’ll take you through some basic principles of coding for Arduino.

Arduino Coding Environment and basic tools

What language is Arduino?

Arduino code is written in C++ with an addition of special methods and functions, which we’ll mention later on. C++ is a human-readable programming language. When you create a ‘sketch’ (the name given to Arduino code files), it is processed and compiled to machine language.

Arduino IDE

The Arduino Integrated Development Environment (IDE) is the main text editing program used for Arduino programming. It is where you’ll be typing up your code before uploading it to the board you want to program. Arduino code is referred to as sketches.

Note: It’s important to use the latest version of Arduino IDE. From time to time, check for updates here.

Arduino code example

As you can see, the IDE has a minimalist design. There are only 5 headings on the menu bar, as well as a series of buttons underneath which allow you to verify and upload your sketches. Essentially, the IDE translates and compiles your sketches into code that Arduino can understand. Once your Arduino code is compiled it’s then uploaded to the board’s memory.

All the user has to do to start compiling their sketch is press a button (a guide to this can be found below).

If there are any errors in the Arduino code a warning message will flag up prompting the user to make changes. Most new users often experience difficulty with compiling because of Arduino’s stringent syntax requirements. If you make any mistakes in your punctuation when using Arduino, the code won’t compile and you’ll be met with an error message.

Serial Monitor and Serial Plotter

Arduino serial monitor can be opened by clicking on the magnifying glass icon on the upper right side of the IDE or under tools. The serial monitor is used mainly for interacting with the Arduino board using the computer, and is a great tool for real-time monitoring and debugging. In order to use the monitor, you’ll need to use the Serial class.

The code you download from has a test section that helps you test each components using the serial monitor, as you can see in the screenshot below:

Arduino serial plotter is another component of the Arduino IDE, which allows you to generate a real-time graph of your serial data. The serial plotter makes it much easier for you to analyze your data through a visual display. You’re able to create graphs, negative value graphs, and conduct waveform analysis.

Debugging Arduino Code and Hardware

Unlike other software programming platforms, Arduino doesn’t have an onboard debugger. Users can either use third-party software, or they can utilize the serial monitor to print Arduino’s active processes for monitoring and debugging.

By using the Serial class, you can print to the serial monitor, debugging comments and values of variables. On most Arduino models, this will be using serial pins 0 and 1 which are connected to the USB port.

Code Structure


In Arduino, much like other leading programming platforms, there are built-in libraries that provide basic functionality. In addition, it’s possible to import other libraries and expand the Arduino board capabilities and features. These libraries are roughly divided into libraries that interact with a specific component or those that implement new functions.

To import a new library, you need to go to Sketch > Import Library

In addition, at the top of your .ino file, you need to use ‘#include’ to include external libraries. You can also create custom libraries to use in isolated sketches.

Pin Definitions

To use the Arduino pins, you need to define which pin is being used and its functionality. A convenient way to define the used pins is by using:

‘#define pinName pinNumber’.

The functionality is either input or output and is defined by using the pinMode () method in the setup section.



Whenever you’re using Arduino, you need to declare global variables and instances to be used later on. In a nutshell, a variable allows you to name and store a value to be used in the future. For example, you would store data acquired from a sensor in order to use it later. To declare a variable you simply define its type, name and initial value.

It’s worth mentioning that declaring global variables isn’t an absolute necessity. However, it’s advisable that you declare your variables to make it easy to utilize your values further down the line.


In software programming, a class is a collection of functions and variables that are kept together in one place. Each class has a special function known as a constructor, which is used to create an instance of the class. In order to use the functions of the class, we need to declare an instance for it.


Every Arduino sketch must have a setup function. This function defines the initial state of the Arduino upon boot and runs only once.

Here we’ll define the following:

  1. Pin functionality using the pinMode function
  2. Initial state of pins
  3. Initialize classes
  4. Initialize variables
  5. Code logic


The loop function is also a must for every Arduino sketch and executes once setup() is complete. It is the main function and as its name hints, it runs in a loop over and over again. The loop describes the main logic of your circuit.

Note: The use of the term ‘void’ means that the function doesn’t return any values.

How to program Arduino

The basic Arduino code logic is an “if-then” structure and can be divided into 4 blocks:

Setup — will usually be written in the setup section of the Arduino code, and performs things that need to be done only once, such as sensor calibration.

Input — at the beginning of the loop, read the inputs. These values will be used as conditions (“if”) such as the ambient light reading from an LDR using analogRead().

Manipulate Data — this section is used to transform the data into a more convenient form or perform calculations. For instance, the AnalogRead() gives a reading of 0-1023 which can be mapped to a range of 0-255 to be used for PWM.(see analogWrite())

Output — this section defines the final outcome of the logic (“then”) according to the data calculated in the previous step. Looking at our example of the LDR and PWM, turn on an LED only when the ambient light level goes below a certain threshold.

Arduino Code libraries

Library Structure

A library is a folder comprised of files with C++ (.cpp) code files and C++ (.h) header files.

The .h file describes the structure of the library and declares all its variables and functions.

The .cpp file holds the function implementation.

Importing Libraries

The first thing you need to do is find the library you want to use out of the many libraries available online. After downloading it to your computer, you just need to open Arduino IDE and click on Sketch > Include Library > Manage Libraries. You can then select the library that you want to import into the IDE. Once the process is complete the library will be available in the sketch menu.

In the code provided by instead of adding external libraries like mentioned before, we provide them with the firmware folder. In this case, the IDE knows how to find them when using #include.

From Software to Hardware

There is a lot to be said of Arduino’s software capabilities, but it’s important to remember that the platform is comprised of both software and hardware. The two work in tandem to run a complex operating system.

Code → Compile → Upload → Run

At the core of Arduino, is the ability to compile and run the code.

After writing the code in the IDE you need to upload it to the Arduino. Clicking the Upload button (the right-facing arrow icon), will compile the code and upload it if it passed compilation. Once your upload is complete, the program will start running automatically.

You can also do this step by step:

  1. First, compile the code. To do this simply click the check icon (or click on sketch > Verify / Compile in the menu bar.

As you can see, the check icon is located in the top left underneath the “File” tag in the menu section.

Once you’ve done this, Arduino will start to compile. Once it’s finished, you’ll receive a completion message that looks like this:

As you can see, the green line at the bottom of the page tells you that you’re “done compiling”. If your code fails to run, you’ll be notified in the same section, and the problematic code will be highlighted for editing.

Once you’ve compiled your sketch, it’s time to upload it.

  1. Choose the serial port your Arduino is currently connected to. To do this click on Tools > Serial port in the menu to designate your chosen serial port (as shown earlier above). You can then upload the compiled sketch.
  2. To upload the sketch, click on the upload icon next to the tick. Alternatively you can go the the menu and click File> upload. Your Arduino LEDS will flicker once the data is being transferred.

Once complete, you’ll be greeted with a completion message that tells you Arduino has finished uploading.

Setting Up Your IDE

In order to connect an Arduino board to your computer you need a USB cable. When using the Arduino UNO, the USB transfers the data in the program directly to your board. The USB cable is used to power your arduino. You can also run your Arduino through an external power source.

Before you can upload the code, there are some settings that you need to configure.

Choose your board — You need to designate which Arduino board you’re going to be using. Do this by click Tools > Board > Your Board.

Choose your processor- there are certain boards (for example Arduino pro-mini) for which you need to specify which processor model you have. Under tools > processor > select the model you have.

Choose your port — to select the port to which your board is connected, go to tools > Port > COMX Arduino (This is Arduino’s serial port).

How to Install Non-Native Boards (e.g. NodeMCU)

Some board models are not pre-installed in the Arduino IDE, therefore you’ll need to install them before you can upload code.

To install a non-native board such as NodeMCU, you need to:

  1. Click on tools > Boards > Boards Manager
  2. Search for the board you want to add in the search bar and click “install”.

Some boards cannot be found through the Board Manager. In this case, you’ll need to add them manually. In order to do this:

  1. Click on Files > Preferences
  2. In the Additional Boards Manager field, paste the URL of the installation package of your board. For instance, for nodeMCU, add the following URL:
  3. Click OK
  4. Go to tools > Boards > Boards Manager
  5. Search for the board you want to add in the search bar and click “install”.

Once you’ve completed this step, you will see the installed boards in the boards’ list under tools.

Note: the process may differ slightly for different boards.

Arduino: An Extremely Versatile Platform

Arduino is far more than just a simple microcontroller. With an expansive IDE and a vast array of hardware configurations, Arduino is truly a diverse platform. The variety of its libraries and its intuitive design makes it a favorite for new users and experienced makers alike. There are thousands of community resources to help you get started with both hardware and software.

As you advance your skills, you may face problems that require debugging, which is a weak spot of the Arduino IDE. Luckily, there are several tools and methods to debug Arduino hardware and software. In the next article, we’re going to look at how to debug Arduino (and how to test Arduino code) as well as how to use simulators and emulators.