Arduino: How to Program It: Basics for Beginners

0
(0)

What is Arduino and where to start learning it?

Arduino—programming you can touch. The board allows you not only to work with code but also to implement it in the physical world. For example, you can program the board to blink LEDs or turn it into a musical instrument. We’ll explore how to start programming on Arduino from scratch, which IDEs are suitable for working with the board, and provide code examples. 

What is Arduino?

Arduino is a microcontroller-based hardware platform designed for developing smart devices and automated systems. Using Arduino, you can program your own magnetic door lock, build a robot with voice recognition, or assemble an automatic pet feeder. Additional modules from third-party manufacturers can be connected to the main board, equipping the system with a display, sensors, batteries, and wireless communication.

457w47

This is what an Arduino board looks like. Photo: author of the article

Arduino was invented in Italy in the early 2000s. The system was designed to quickly and easily teach programming and circuit design, so the platform was designed from the start to be flexible so it could be used in any school or club setting.

All Arduino designs are open source, so in addition to the original boards, you can find Chinese knockoffs. The company always publishes the drawings, schematics, and software for its designs. As a result, these knockoffs are practically indistinguishable from boards made in Italy.

What is Arduino programmed with?

Code for all Arduino boards is written in the Arduino language, which is based on C++ and the Wring framework. The platform’s creators chose C++ for its speed and high efficiency when developing for memory-constrained devices. The Wring framework is responsible for controlling the Arduino hardware. Code is compiled using avr-gcc.

Some boards support programming in MicroPython. To do this, you need to manually install the necessary environment and prepare the controller hardware to process such code.

Programming is most convenient in integrated development environments. Arduino boards come with the Arduino IDE. Available for Windows, Linux, and macOS, it brings together all the tools you might need when developing your own projects. In the Arduino IDE, you can write code, optimize board performance, get performance data, install third-party libraries, and develop your own. The Arduino IDE can be downloaded from the company’s official website; the project’s code is open-source and published on GitHub.

656

This is what the Arduino IDE interface looks like.

If you can’t install the Arduino IDE, you can program the board in your browser using the cloud development environment . It supports working with code, sending written code to the board, interacting with libraries, and monitoring. The cloud IDE’s capabilities are limited, and for full access, you need to purchase an Arduino Cloud subscription.

756737

This is what the cloud IDE for Arduino looks like.

You can also develop Arduino code in Microsoft’s Visual Studio Code editor. This is possible thanks to the third-party PlatformIO plugin , which simplifies interaction with the hardware. The plugin is free and provides features for developing, debugging, and flashing the boards.

Arduino Visual Programming

Beginners may find it difficult to immediately begin coding in Arduino C due to the language’s complex C++ foundation. Not all boards support MicroPython, so a visual programming approach based on drag-and-drop can be a solution. This approach is useful not only for beginners but also for children in programming classes.

The Massachusetts Institute of Technology’s S4A project is a modification of the visual programming language for Arduino. It can be used to assemble code blocks into ready-to-use firmware for proprietary boards. The project hasn’t been updated in a while, but it still works reliably. Russian is available, and detailed installation documentation is available.

The ArduBlock project , developed by Russian developers, is actively supported and offers up-to-date features for most Arduino and ESP boards. Block-based programming, along with lessons and instructions in Russian, are available in the browser. Together with ArduBlock, the project’s creators also release starter kits for beginners.

rgry

This is what the ArduBlock visual programming service for Arduino looks like.

Arduino Programming Basics

The Arduino community commonly refers to a project code file as a sketch. Sketches are written according to specific rules that ensure proper operation of the hardware and execution of commands. The basic structure looks like this:

#include “name”
void setup () {
}
void loop () {
}

At the very beginning of the sketch, third-party libraries are included in the main file using a directive #includeand the library name. The name can be specified using quotation marks (“”) or check marks (<>). In the former case, the library file is first searched in the sketch folder and then in the folder containing the installed libraries. If you use check marks, the system will search for the specified file only in the folder containing the installed libraries.

Next comes the function setup(), which is executed each time the sketch is run on the Arduino. At this point, the system sets the board’s inputs and outputs to their operating mode, retrieves variable values, and prepares the board for the rest of the code.

The function loop()loops and controls the Arduino. In this section, developers write the main code of the sketch, which implements the logic of the entire project. Execution loop()starts immediately after setup(). These two functions are required in every project sketch, even if the functions contain no instructions. Without them, the code cannot run on the Arduino.

Comments and delimiters

Arduino is programmed in a language based on C++, so it inherits many of its features. For example, single-line comments are specified using double slashes (//). The compiler will ignore all text within a comment; slash-delimited text is typically used to explain how the code works. Comments are primarily for the people writing and using the code, not the computer.

To comment multiple lines at once, use the slash-asterisk construct (/* comment */). This construct must be closed, otherwise the compiler will not be able to find the end of the comment.

// Single-line comment
// Second single-line comment
/*
And this is already
Multi-line comment
*/

All instructions must be separated by a semicolon (;). This feature also came to Arduino syntax from C++. If you don’t do this, the code won’t build and the sketch won’t upload to the board.

Arduino variables

Variables in Arduino, like in all programming languages, are used to store data. When programming Arduino, we must specify the variable type before its name. The following data types exist:

Data TypeDescriptionExample
booleanA logical type that contains the values true or falseboolean logic = true
byteNumeric data type for small numbers from 0 to 255byte number = 255
intIntegers from -32768 to 32767int number = 32767
unsigned intLike int, but with a larger range and no negative values (0 to 65535)unsigned int number = 65535
floatFloating-point numbers (numbers with decimals)float number = 22.15

Arduino Operators

OperatorDescriptionExample
ifA conditional operator that checks whether the specified value is true. For example, 3 is greater than 2, so this condition will evaluate to true.if (3 > 2) { action }
if elseA conditional operator that performs two different actions: for a true value and for a false value.if (3 > 2) { action } else { action }
forA loop designed to perform actions repeatedly. For example, it could be used to loop through an array of LEDs and set the brightness of each one.for (int i = 0; i < KEY_COUNT; ++i) { action }
whileA loop that executes as long as its condition remains true. For example, it will execute while a variable is greater than or less than a certain value.while (number > 5) { action }

Uploading firmware to the board

Let’s imagine we’ve written and debugged the code, now we need to test it on hardware. To do this, we need to somehow send the code to the Arduino board. The proprietary development environment provides a convenient way to flash boards for this purpose.

First, connect the board to the computer via USB. Each generation and type of Arduino uses its own connection standard. This is important to keep in mind. In the running IDE, expand the list and find the board.

65u8

This is how uploading code to a board works in the Arduino IDE.

Select and click the button with the arrow icon. The board’s LEDs will start blinking. If the firmware was successfully flashed, a message will appear in the terminal.

Let’s blink the LED

In the programming world, it’s common to display “Hello, World!” as the first program. In the Arduino world, a tradition has developed of blinking an LED located on the board. Beginners use this sketch to begin learning microcontroller programming, while professionals use it to check boards for defects.

To begin working on the project, launch the Arduino IDE. The required sketch is included in the IDE’s example library. You can find it under File → Examples → 01. Basics → Blink. Once selected, the code will appear in the editor window, the first lines of which are replaced by an extensive comment describing the project. You can delete this comment immediately to avoid it getting in the way. Let’s examine the code in detail:

 

// the setup function runs once when you press reset or power the board
void setup () {
// initialize digital pin LED_BUILTIN as an output.
pinMode ( LED_BUILTIN, OUTPUT ) ;
}
// the loop function runs over and over again forever
void loop () {
digitalWrite ( LED_BUILTIN, HIGH ) ; // turn the LED on (HIGH is the voltage level)
delay ( 1000 ) ; // wait for a second
digitalWrite ( LED_BUILTIN, LOW ) ; // turn the LED off by making the voltage LOW
delay ( 1000 ) ; // wait for a second
}

In the function, setup()The LED_BUILTIN pin is configured as an output. This means we won’t receive anything through it and will only use it to transmit parameters. Pins LED_BUILTIN and 13 are connected. Replacing LED_BUILTIN with 13 in the code won’t change anything.

This function loop()is used to control the pin we initialized above. First, we apply 5 volts to it using HIGH, pause for 1000 milliseconds using delay(), and then remove the voltage. The function loop()repeats in a loop, so all instructions in the code will execute as long as the board has power.

Assembling a piano

We already know almost all the theory behind Arduino programming and even tried writing our own “Hello, World!”, so now we can move on to more complex projects. Let’s try building a simple musical instrument similar to a piano.

Scheme

The project’s schematic is very simple, and to assemble it you’ll need three buttons, three 10kOhm resistors, a buzzer, and a bunch of connecting wires. We’ll be assembling the circuit on a breadboard. This makes prototyping faster and eliminates the need to re-solder everything with each new version of the circuit.

All elements should be connected in the following sequence, observing the pin order:

69990

If you have a board at hand, try to assemble everything exactly as in the picture.

Code

The entire project code looks like this:

#define BUZZER 13 // beeper on pin 13
#define KEY_FIRST 7 // first key pin
#define KEY_COUNT 3 // total keys
void setup () {
pinMode ( BUZZER, OUTPUT ) ;
}
void loop () {
for ( int i = 0; i < KEY_COUNT; ++i ) {
int keyPin = i + KEY_FIRST;
boolean keyUp = digitalRead ( keyPin ) ;
if ( !keyUp ) {
int frequency = 3500 + i * 500;
tone ( BUZZER, frequency, 20 ) ;
}
}
}

You can immediately retype it into the development environment and try uploading it to the board. If everything is successful, a sound will play when you press the buttons. Now let’s examine the code in more detail.

At the very beginning, we define names for the pins we’ll be using. This is done using the directive #define. Then, we specify the name in capital letters and the pin number on the Arduino board. That’s it! After this, we can access the pin in our code by its name, not its number. This is especially convenient for large projects when it’s difficult to remember which pin does what.

#define BUZZER 13 // beeper on pin 13
#define KEY_FIRST 7 // first key pin
#define KEY_COUNT 3 // total keys

Next comes the familiar setup() function. Here we perform the preliminary board settings. In this project, we set the buzzer pin to output mode because we won’t be receiving anything through it. We need to emit sound.

void setup () {
pinMode ( BUZZER, OUTPUT ) ;
}

It’s important to note that all pins operate in input mode by default. Therefore, we don’t specify that each pin is used as an input in the project.

Now comes the most important part of the code—the function loop(), which executes all the logic. In the case of the piano, we loop through all the buttons in a for loop. Knowing the button number, we calculate its pin. Then we read its value to find out whether the button is pressed or not. If it is pressed, we play a sound. To read the button value, we use the function digitalRead(), and to play the sound, we use tone().

void loop () {
for ( int i = 0; i < KEY_COUNT; ++i ) {
int keyPin = i + KEY_FIRST;
boolean keyUp = digitalRead ( keyPin ) ;
if ( !keyUp ) {
int frequency = 3500 + i * 500;
tone ( BUZZER, frequency, 20 ) ;
}
}
}

Result

  • Programming Arduino isn’t as difficult as it might seem. The platform’s developers have made every effort to make it easy to write code, rather than figuring out how the board works.
  • Arduino has been around for many years and is actively supported by the community, so you can find libraries to solve almost any problem.
  • The platform is also supported by third-party manufacturers, so you can find a wide range of sensors, probes, and modules in stores that expand the capabilities of Arduino.
  • Developers are developing not only the platform itself, but also the tools for working with it.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?


Explore More IT Terms


Share this term: Facebook X LinkedIn WhatsApp Email

Leave a Reply

Your email address will not be published. Required fields are marked *