Code

Arduino – What It Is and How It Works: A Beginner's Guide to Programming

Arduino – What It Is and How It Works: A Beginner's Guide to Programming

Practical course: "Microcontroller Programmer"

Learn more

What is Arduino

Arduino is a universal platform for developing electronic devices, which is suitable for both beginners and experienced developers. It provides excellent opportunities for learning programming, electronics, as well as for creating prototypes of real gadgets and implementing various hobby projects. The platform includes a wide range of microcontrollers, development software, and an extensive community, making learning and project creation more accessible and fun.

  • The hardware part is a board with a microcontroller, such as the Arduino Uno;
  • The software part is the free Arduino IDE development environment and built-in libraries that simplify working with the hardware.
The Arduino Uno is one of the most popular boards in the line. Image: Arduino

Arduino stands out for its accessibility and ease of use. To get started, you only need an Arduino board, a USB cable, and a computer. Thanks to a large number of ready-made libraries and an intuitive programming language, even beginner users can quickly create a functional device, such as a wheeled robot. This tool is ideal for learning the basics of electronics and programming, making it a popular choice among hobbyists and students.

There are many devices based on the Arduino platform. These devices demonstrate the wide range of applications for Arduino in various fields. For example, you can find automated irrigation systems that monitor soil moisture levels and turn the pump on or off as needed. Another popular example is a smart thermometer that displays real-time temperature and humidity data. There are also robotics-related projects, such as mobile robots capable of avoiding obstacles and following preset routes. Arduino is used to create smart home systems, such as lighting and security controls, making it an ideal tool for developers and enthusiasts. These examples highlight the versatility of the Arduino and its ability to bring a variety of ideas and projects to life.

Smart FeederImage: Arduino_Genuino / Project Hub
Game machine with matrix displayImage: mircemk / Project Hub
RobocatFrame: PetoiCamp / YouTube
Home automated farmPhoto: londonium2021 / Project Hub

The History of Arduino: Intrigue and Scandals

In the early 2000s, Telecom Italia and Olivetti launched interaction design courses in the Italian city of Ivrea. These courses taught students how to design devices with intuitive interfaces based on an analysis of user behavior. This was an important step in the development of design, as the emphasis on user interaction contributed to the creation of more efficient and user-friendly technologies. The courses drew attention to the importance of user experience in product development, which subsequently had an impact on the entire industry.

In the course, students studied the BASIC Stamp platform, where they wrote code in PBASIC, a dialect of BASIC. This process proved challenging for participants whose primary specialization was design, not programming. The course provided an opportunity to master the basics of programming and develop technical skills.

BASIC Stamp installed in a debug board Photo: Marcin1988 / Wikimedia Commons

Course graduate Hernando Barragan created an alternative Wiring platform in 2004, which includes a board with Firmware and support for programming in simplified C++. This development significantly simplified the process of creating and developing gadgets, making it more accessible and faster. The Wiring platform was a major step in the world of electronics and programming, opening up new opportunities for developers and enthusiasts.

Wiring and the subsequent Arduino platform are open source, which played a key role in their popularity. This allowed developers and enthusiasts around the world to adapt and improve the project, creating new solutions and devices. The open source nature of the code has become the basis for many compatible platforms, which has significantly expanded the possibilities of using Arduino in various fields, from educational projects to professional development.

Wiring board Photo: Hernando Barragán

Wiring boards quickly gained popularity on the course, but their cost remained high - about $60 per unit. In response, Barragan's supervisor, Massimo Banzi, created a fork of the project, replacing the expensive microcontroller with a more affordable ATmega8 while retaining the Wiring software. This resulted in the development of an Arduino prototype, initially dubbed Wiring Lite. Arduino has become the basis for many projects and applications in the field of electronics and programming, thanks to its accessibility and ease of use.

Prototype Arduino board called Wiring Lite Photo: Hernando Barragán

The name Arduino comes from a local bar that became a meeting place for students and teachers. This bar, in turn, was named after the King of Italy, Arduino of Ivrea.

In 2008, Arduino LLC, founded by Banzi, was registered in the United States. This company held the rights to the Arduino brand. Boards were manufactured by third-party factories under license, which contributed to the distribution and popularization of Arduino products worldwide.

Wiring and the subsequent Arduino platform became popular due to their open source nature. This allowed developers and enthusiasts to adapt and improve the project, leading to the creation of many compatible platforms and applications. Open source code contributed to the active development of a community where users could share their ideas and solutions, which, in turn, encouraged innovation in the fields of electronics and programming.

As Arduino's popularity grew, the team needed to establish legal entities in other countries. When attempting to register a company in Italy, it was discovered that the Arduino brand was already registered to Gianluca Martino, one of the project's co-founders and the owner of the factory that manufactured the boards. He was discovered to have secretly registered companies under the name Arduino SRL in various countries. This case highlights the importance of carefully protecting brands and intellectual property in the international business environment.

The conflict arose from Arduino LLC's management's choice of a fabless manufacturing model. Under this approach, engineers design boards and tools, and any factory can manufacture them. Martino, in turn, feared that his factory would be unable to compete with Chinese manufacturers and sought to keep production in-house.

The situation resulted in Arduino LLC being able to sell its boards exclusively in the United States, while Arduino SRL sold in other countries. This trade war lasted until October 1, 2016. At the World Maker Faire conference, Massimo Banzi and Federico Musto, CEO of Arduino SRL, announced the merger of their companies into a single legal entity – Arduino AG. This merger has simplified sales processes and improved cooperation between different regions, which has had a positive impact on the development of the Arduino brand on a global scale.

Massimo Banzi and Federico Musto announce the merger of two Arduinos into a third Photo: Arduino Team

Arduino offers a variety of boards and ready-made kits for enthusiasts, educational institutions, and programming enthusiasts. The company also produces a line of industrial controllers used in warehouse and factory automation. Arduino's primary goal is to create affordable solutions to make developing smart devices a fun and accessible hobby for everyone.

Board Anatomy

In this overview, we'll look at the pins, interfaces, and buttons found on the third-generation Arduino Uno board. The Arduino Uno is one of the most popular and widely used boards in the world. For a deeper understanding of its design and functionality, we recommend reading the official documentation. Here we will present the key elements that will help you in working with the Arduino Uno.

The main elements of the Arduino Uno board Photo: Skillbox Media

The presented photograph shows…

  • Reset button (1) - a button for restarting the loaded code, if, for example, the board stopped responding correctly to commands.
  • Digital pins (2) are general-purpose pins that can generate and read signals. You can connect sensors, motors, buttons, and other controls to them.
  • USB-B connector (3) is the port with which the board can be connected to a computer and programmed.
  • ATmega328P controller (4) is the “brain” of the Arduino Uno, which performs all calculations and operations. You could say that it replaces the processor and memory here, like the central unit in a regular computer, only more compact and simpler.
  • Power connector (5) is a port for connecting the board to a battery or outlet.
  • Power pins (6) are pins with which you can power sensors, motors, and other elements connected to the Uno.
  • Analog pins (7) are pins that can only read signals. Suitable for connecting sensors.

Each digital and analog pin has specific current and voltage limits. Before connecting external devices, it is important to read the technical documentation to avoid damage to components and ensure proper operation of the circuit. Correctly adhering to these parameters will ensure the reliability and longevity of your device.

Arduino boards differ in the number of pins, form factor, and power. In this article, we will consider the various Arduino models and provide recommendations for choosing the most suitable board for your projects.

Which Arduino board to choose?

Our company's online store offers a wide range of boards for developing robots, smart devices, compact gadgets, and industrial equipment. This variety can be confusing, so we suggest you consider the main characteristics of the most popular Arduino solutions. This will help you make an informed choice and purchase exactly what you need for your personal workshop.

The ATmega328P microcontroller is a popular chip that is widely used in various electronic projects and developments. This 8-bit microcontroller from Atmel (now part of Microchip Technology) offers high performance and low power consumption, making it an ideal choice for embedded systems.

The ATmega328P has 32 KB of flash memory for program storage, 2 KB of static random-access memory (SRAM), and 1 KB of non-volatile memory (EEPROM). It supports clock rates of up to 20 MHz and offers 23 programmable input/output (I/O) ports, providing flexibility in connecting a variety of sensors and actuators.

The ATmega328P microcontroller is often used in boards such as the Arduino Uno, making it accessible to beginner developers and hobbyists. Its ease of programming using the C/C++ language and the availability of an extensive library of development tools facilitate rapid prototyping and implementation of ideas.

Furthermore, the ATmega328P supports various communication interfaces such as SPI, I2C, and UART, expanding its capabilities for integration into complex systems. Thanks to its reliability and versatility, the ATmega328P microcontroller continues to be the number one choice for many electronics and automation projects.

Memory capacity is 32 KB of flash memory and 2 KB of SRAM. Flash memory provides long-term data storage, while SRAM is used for fast data access during device operation. These memory characteristics play a significant role in device performance and functionality, providing a balance between storage capacity and speed.

This product is ideal for developing robots and a variety of smart devices. It delivers high performance and reliability, making it an excellent choice for projects involving automation and smart technology.

Price ranges from $27 to $55.

Documentation is an important resource providing information about a product, service, or process. It serves as a guide for users, developers, and administrators, ensuring an understanding of functionality and features. Quality documentation helps minimize errors and facilitates the learning process. It is important that it is structured, up-to-date, and easily accessible. Effective documentation improves the user experience and contributes to increased customer satisfaction. Creating and maintaining documentation requires a systematic approach and regular updates to keep up with product changes and user needs.

Arduino Uno R3 board. Image: Arduino Docs

The Arduino Uno is one of the most popular and versatile microcontroller boards on the market. Она оснащена достаточным количеством портов для подключения множества датчиков, моторов, сервоприводов и контроллеров. Если вы хотите начать изучение программирования для Arduino, смело выбирайте плату Uno. Она идеально подходит как для учебных экспериментов, так и для разработки полноценный проектов. Благодаря своей простоте в использовании и широкому сообществу поддержки, Arduino Uno станет отличным стартом для освоения основ электроники и программирования.

Микроконтроллер ATmega328 является одним из самых популярных и широко используемых микроконтроллеров в мире электроники. Он основан на архитектуре AVR и предлагает высокую производительность при низком потреблении энергии. ATmega328 обладает 32 КБ флеш-памяти для хранения программ, 2 КБ оперативной памяти и 1 КБ памяти для данных. Благодаря 23 входам/выходам, он обеспечивает гибкость в подключении различных датчиков и исполнительных устройств.

Этот микроконтроллер часто используется в проектах, связанных с робототехникой, автоматизацией и разработкой устройств на базе Arduino. Он поддерживает работу с различными интерфейсами, такими как SPI, I2C и UART, что делает его идеальным выбором для создания сложных электронных систем. ATmega328 также характеризуется высокой надежностью и устойчивостью к внешним воздействиям, что делает его подходящим для использования в различных условиях.

Выбор ATmega328 для вашего проекта обеспечит стабильную работу и возможность масштабирования в будущем. С его помощью вы можете реализовать множество интересных идей, от простых LED-проектов до сложных автоматизированных систем.

Объем памяти составляет 32 КБ флеш-памяти и 2 КБ SRAM.

This project is ideal for use on compact devices, providing convenience and efficiency. With its optimized design and functionality, it handles space-constrained tasks perfectly. Choose our solution for maximum performance on small screens and devices with limited resources.

Price ranges from $15 to $40.

Documentation is a structured set of information that explains the functionality, features, and use of a specific product or service. It is important that documentation is clear and accessible to users, as it serves as the primary source of product knowledge. Well-written documentation includes instructions, usage examples, troubleshooting tips, and frequently asked questions. It not only helps users effectively interact with the product but also contributes to a better experience. Proper documentation design and organization play a key role in its perception and usefulness. Documentation should be updated in parallel with product development to ensure the information remains relevant and in line with the latest changes. Effective documentation can significantly reduce the number of support calls, as users can find answers to their questions on their own. Therefore, it is important to pay attention to every aspect of creating and updating documentation.

Arduino Nano BoardImage: Arduino Docs

The Arduino Nano is a compact alternative to the Uno board. Despite the smaller number of ports and limited memory, its size allows for easy integration into almost any project. An additional benefit is the ability to install the Arduino Nano on a breadboard, making it ideal for prototyping and developing various electronic devices.

The ATmega2560 microcontroller is a powerful and versatile solution for various electronics and programming projects. It belongs to the AVR family and offers 256 KB of flash memory, allowing for storing fairly large program codes. The ATmega2560 also features 8 channels of a 10-bit ADC, providing high-precision analog readings, and 54 digital I/O pins, making it ideal for complex circuits.

This microcontroller supports various interfaces, such as I2C, SPI, and UART, facilitating integration with other devices and modules. It is widely used in robotics, automation systems, and embedded systems due to its reliability and high performance.

The ATmega2560 has the ability to operate at various voltages and temperatures, making it suitable for applications requiring stability and durability. Using this microcontroller opens up wide possibilities for developers and engineers, allowing them to implement innovative ideas and projects.

The memory capacity is 256 KB of flash memory and 8 KB of SRAM. These characteristics provide sufficient space for storing data and performing operations. Flash memory allows information to be retained even when the power is off, while SRAM provides fast access to data during device operation.

This product is ideal for projects involving devices equipped with many sensors. It provides efficient control and data processing, making it an excellent choice for complex systems requiring the integration of various sensors. Use it in your development to improve the functionality and performance of your devices.

The price ranges from $50 to $70.

Documentation is an essential tool for effectively understanding and using a product or service. It provides users with the necessary information about the functions, features, and methods of interacting with the product. Properly written documentation facilitates the learning process and reduces the number of errors during use.

Quality documentation includes clear instructions, usage examples, answers to frequently asked questions, and troubleshooting tips. This not only promotes better information comprehension but also increases user satisfaction.

It is also worth noting that documentation should be regularly updated to reflect changes and improvements to the product. Integrating SEO optimization into documentation text helps improve the visibility and accessibility of information in search engines, allowing users to find the materials they need faster.

Creating structured and understandable documentation is key to the successful use of any product, as it serves as the primary source of knowledge for users and supports them throughout the process of use.

Arduino Mega board. Image: Arduino Docs

The Arduino Mega is a powerful board with more pins, a more powerful microcontroller, and increased memory. It is ideal for complex projects that require connecting numerous sensors and performing resource-intensive calculations. Examples of such projects include walking robots using dozens of servos. However, given the board's higher cost, using it for education may not be practical. For the initial stages of learning to program and work with Arduino, the Uno board is quite sufficient.

The ATmega32U4 microcontroller is a powerful and versatile device, ideal for a variety of electronics and robotics projects. This 8-bit microcontroller, developed by Atmel, stands out for its integrated USB support, allowing it to function as a USB device without the need for additional components. Based on the AVR architecture, the ATmega32U4 offers 32 KB of flash memory, 2 KB of RAM, and 1 KB of EEPROM, ensuring high performance and ample memory for storing programs and data.

One of the key advantages of the ATmega32U4 is its 26 I/O ports, allowing for the connection of a wide range of peripherals. The microcontroller also supports various interfaces, such as SPI, I2C, and UART, significantly expanding its functionality. Additionally, the ATmega32U4 includes built-in timers and an ADC, making it an excellent choice for projects requiring precise time management and analog signal processing.

Using the ATmega32U4 in projects allows developers to create innovative solutions for automation, control, and user interaction. Compatibility with popular platforms like Arduino makes this microcontroller ideal for both beginners and experienced engineers looking to bring their electronics ideas to life.

The device's memory includes 32 KB of flash memory and 2.5 KB of SRAM. Flash memory stores data and firmware, ensuring reliable retention even when power is removed. SRAM, in turn, is used for temporary data storage, which contributes to the device's speed and efficiency. The combination of these two memory types provides optimal performance and functionality.

This material is ideal for projects involving keyboards, mice, and game controllers. It will provide high performance and reliability, which is especially important for gamers and professionals working with these devices. With its help, you will be able to create high-quality and durable products that meet user needs.

The price is $22.

Documentation is an important tool for users and developers, providing access to necessary information about a product or service. It includes instructions, guides, technical specifications, and frequently asked questions. Properly designed documentation helps reduce the number of support requests and improve the user experience.

To create effective documentation, it is necessary to consider the target audience and present information in a clear and accessible form. Including examples, illustrations, and step-by-step instructions can significantly increase its value. It is also important to regularly update materials to keep them in line with current changes in the product or service.

Optimizing documentation for search engines (SEO) includes the use of keywords, meta tags, and structured data. This helps users find the information they need more easily and improves the visibility of documentation in search engines.

Good documentation not only simplifies the learning process, but also helps improve user satisfaction, which in turn can lead to increased loyalty and recommendations.

Arduino Micro Board Image: Arduino Docs

Arduino Micro is a compact board that can operate in HID (Human Interface Device). This functionality allows the Arduino Micro to be used to create custom devices, such as keyboards, mice, steering wheels for racing simulators, or controllers for gaming consoles. This versatility makes the Arduino Micro an ideal choice for developers and enthusiasts who want to bring their ideas to life in the field of interacting with computers and gaming systems.

Arduino offers not only educational and hobbyist solutions but also specialized boards for professional use. The Arduino Pro line is designed for industrial applications, including process automation in factories and warehouses. Pro boards are typically black, while standard models have a blue tint. These devices provide reliability and high performance, making them ideal for use in challenging industrial environments.

The Arduino Pro line includes several key families designed for a variety of projects and applications. These families provide high performance and reliability, making them ideal for professional use. Each family offers unique features and capabilities, allowing developers to choose the optimal solution for their needs. Importantly, Arduino Pro is focused on supporting complex and scalable projects in the fields of IoT, automation, and control.

  • Portenta is a set of high-performance boards and modules for industrial projects. They can simultaneously run low-level code and scripts in MicroPython or JavaScript.
  • Nicla is a compact, low-power board for AI projects. For example, the Nicla Vision board can be used to build a system for automatic order sorting in a warehouse.
  • Opta is a series of programmable logic controllers in the microPLC form factor. They have Ethernet, Wi-Fi, Bluetooth, and a DIN rail mount for mounting in electrical cabinets.
Arduino Portenta H7 board Image: Arduino Docs
Board Arduino Nicla VisionImage: Arduino Docs
Arduino Opta BoardImage: Arduino Docs

There are many boards available on marketplaces that are similar in characteristics to the Arduino, but have different names. These devices are not counterfeits, but rather legitimate and functional alternatives. Each of these boards offers unique features and specifications, making them attractive to developers and enthusiasts. The choice among them allows you to find optimal solutions for various electronics and programming projects.

Almost all Arduino boards and firmware are released under an open Creative Commons Attribution ShareAlike license. This allows anyone to create their own Arduino boards. To support developers, the company publishes schematics, drawings, and documentation on its official website. Furthermore, the company is open to large manufacturers launching mass production of similar products. However, it is important to remember that the use of the Arduino name, its derivatives, and logo is strictly prohibited, as these elements are protected by copyright.

Official Arduino Uno board schematic Image: Arduino Docs

Read also:

Creative Commons Licenses: What They Are, How They Work, and What Types Exist

Creative Commons licenses are a tool that allows authors to share their works while setting specific terms of use. These licenses allow authors to retain their copyright while allowing others to use, distribute, and adapt their work.

There are several types of Creative Commons licenses, each with its own characteristics. For example, licenses may permit or prohibit commercial use, require attribution, or permit modifications to the original work.

The main categories of Creative Commons licenses include:
1. CC BY - a license that requires attribution;
2. CC BY-SA - a license that permits modification, provided that the author is credited and a similar license is used for derivative works;
3. CC BY-ND - a license that permits distribution without modification;
4. CC BY-NC - a license that permits non-commercial use with attribution;
5. CC BY-NC-SA - a license for non-commercial use with attribution and a similar license for derivative works;
6. CC BY-NC-ND - The most restrictive license, permitting only non-commercial use without modification and with attribution.

Using Creative Commons licenses significantly simplifies the process of sharing knowledge and cultural works, promoting the accessibility of information and creative content. They play a vital role in the modern world, where information sharing is becoming increasingly important.

The Russian company Amperka offers Iskra boards, which are similar to Arduino with minor modifications. These devices are manufactured according to official designs, ensuring high quality and compatibility. Arduino supports such solutions in the market, recognizing their contribution to the development of open technologies and the accessibility of electronics for developers. Iskra boards are ideal for educational and commercial projects, providing users with the convenience and functionality of the original Arduino.

Iskra Uno - an analogue of Arduino Uno from the company "Amperka" Frame: AmperkaRu / YouTube

When choosing Arduino boards, keep in mind that not all manufacturers добросовестно соблюдают лицензии и соглашения. На маркетплейсах можно встретить множество плат с ценами, значительно ниже официальных. Это зачастую подделки китайских компаний, которые используют логотип Arduino в нарушение правил. Такие платы часто производятся из некачественных материалов или с нарушением технологий, что приводит к их быстрому выходу из строя. Чтобы избежать проблем с качеством и надежностью, рекомендуется приобретать оригинальные платы Arduino только у авторизованных продавцов.

Вот список надежных аналогов Arduino, кроме платформы Iskra от компании «Амперка»:

  • Piranha;
  • RobotDyn;
  • Keyestudio;
  • Adafruit.

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

Оригинальная плата Arduino Uno (слева) и подделка (справа)Изображение: Arduino

В проектах рекомендуется использовать оригинальные платы или аналоги от компаний с хорошей репутацией. Платы от китайских производителей без известного бренда часто отличаются низким качеством, несмотря на их значительно более низкую цену, которая может быть в 5–10 раз ниже. Однако, если ваша цель заключается в том, чтобы просто ознакомиться с разработкой на платформе Arduino, то использование менее дорогих вариантов может быть оправданным. Важно помнить, что качество компонентов влияет на стабильность и надежность вашего проекта.

Какое ещё железо нужно ардуинщику

Для создания увлекательных проектов одной платы недостаточно. Плата является центральным элементом, но ей необходимы дополнительные компоненты для полноценной работы. В этом контексте важно рассмотреть набор инструментов и устройств, которые являются незаменимыми для успешной реализации проектов.

Платы Arduino позволяют подключать различные сторонние модули, датчики и сенсоры, что расширяет их функциональные возможности. Например, для создания метеостанции потребуется дополнительно приобрести термометр, барометр и анемометр. Если ваша цель — собрать робота, вам понадобятся камера, дальномер и моторы. Использование этих компонентов обеспечивает создание уникальных проектов на базе Arduino, открывая широкий спектр возможностей для разработчиков и любителей электроники.

A scattering of various modules and sensors Photo: Skillbox Media

When choosing sensors and modules for a specific device, it is important to consider the tasks at the design stage. It is not recommended to immediately purchase all available devices to connect to the board. Instead, focus on the functional requirements of your project. Over time, you'll accumulate a significant collection of essential electronic components, simplifying future development and improving work efficiency. Choosing the right hardware early on will help avoid unnecessary costs and streamline the design process. Connecting modules and sensors directly to the board can be inconvenient, as the sensors may block access to adjacent pins. To avoid this problem, we recommend using breadboards. These versatile devices are designed for quickly mounting components and simplify the prototyping process. Breadboards provide convenient connections, allowing you to easily reconfigure the circuit and test various components. For experimentation, it's best to use solderless breadboards, also known as breadboards. These boards have an organized contact structure, allowing you to easily connect multiple modules and components. Due to their versatility and convenience, breadboards are an ideal solution for prototyping and testing circuits.

BreadboardPhoto: Skillbox Media

To create your own module, we recommend using a solderable breadboard. This board is a standard printed circuit board with exposed pins on which you can install various electronic components. Breadboards allow for flexible project experimentation and simplify the assembly process, making them an ideal choice for makers and electronics enthusiasts. Dupont cables are used to connect modules and sensors on a breadboard to the Arduino. There are three main types of these cables: male-to-male, female-to-female, and female-to-male. These cables provide reliable and convenient component connections, an essential step in prototyping and electronics development. Choosing the right cable type can simplify the assembly process and improve the efficiency of your Arduino-based projects.

Top to bottom: "male - female", "female - female", and "female - female" Photo: Skillbox Media

Interesting fact: the name "Dupont" This is not the official name of the connector. At the beginning of the 21st century, Chinese manufacturers began mass-producing jumper cables insulated with materials from the American chemical company DuPont. As a result, this name became popular, and now cables with a 2.54 mm pitch are often called DuPont connectors. This term has become widely used among electronics professionals and hobbyists, emphasizing the importance of high-quality materials in cable production.

A shield (from the English word "shield") is an expansion board for Arduino that significantly increases the functionality of a device. Using a shield, you can integrate additional modules, such as Wi-Fi or GPS, which is especially useful if these features are not initially included in the project. Using shields simplifies the development process and significantly expands the capabilities of working with Arduino, allowing you to create more complex and innovative projects.

With shields, Arduino turns into a sandwich, but at least there are no wires sticking out in all directions. Photo: Skillbox Media

A bundle of several modules can effectively replace a shield, However, such a design will be less neat and compact. Expansion boards are most often used for educational purposes, for example, in Arduino development courses. The convenient way of attaching shields allows students to focus on programming without being distracted by complex connection diagrams. Using shields in education promotes the rapid mastery of development basics and makes it easier to experiment with various projects.

Additional tools may be required for mounting electronic components and assembling the final device. Important aspects of the process include the selection of high-quality equipment and adherence to assembly technologies. Basic tools include soldering irons, multimeters, screwdrivers, nippers, and pliers. You may also need a specialized tool for installing connectors and other components. Correct selection and use of these tools will ensure the reliability and durability of the assembled device.

  • Soldering iron. After experimenting on a breadboard, the electrical circuit of the project can be transferred to a printed circuit board. For this, you will need a soldering iron, solder, rosin, and flux.
  • "Third hand". When soldering, it is not always convenient to simultaneously hold a hot soldering iron, solder, the board, and the element you are going to solder. In such cases, a “third hand” comes to the rescue - a tripod, which allows you to secure all the necessary elements and work with them.
“Third hand” with two clamps and a magnifying glass Photo: Dro Kulix / Wikimedia Commons
  • A set of tweezers. Electronic components can be very small, and picking them up by hand isn't always convenient. It's best to use tweezers to avoid accidentally breaking anything.

IDE for Arduino

Arduino programming is possible with any text editor, but using specialized integrated development environments (IDEs) significantly simplifies the process. These environments offer a variety of tools that speed up development and increase its efficiency. In this article, we will look at the most popular IDEs and code editors for Arduino, which will help you optimize the programming process and achieve better results.

Arduino IDE InterfaceScreenshot: Arduino IDE / Skillbox Media

Arduino IDE is the official development environment created by the team Arduino. It offers all the necessary tools for effectively working with Arduino boards. This environment allows you to write code, debug it, optimize it, and upload it to devices, making the development process simple and convenient. The Arduino IDE supports numerous libraries and examples, allowing users to quickly start projects and easily integrate various modules. This environment is ideal for both beginners and experienced developers seeking to create innovative electronic solutions. There are two versions of the official development environment: the updated Arduino IDE 2 and the legacy Arduino IDE Legacy. Both versions are functional, but the Arduino IDE Legacy lacks some modern features, such as automatic code completion and file synchronization with cloud storage. We recommend using the Arduino IDE 2 for more efficient work and access to all modern development tools.

Cloud editor in Arduino CloudScreenshot: Arduino Cloud / Skillbox Media

Arduino Cloud is a cloud platform designed for remote control of connected boards. It's ideal for creating and deploying DIY IoT devices. The platform includes a built-in code editor that allows you to write, debug, and upload sketches to boards directly from the browser. One of the key advantages of Arduino Cloud is the ability to access the editor from mobile devices, which makes development more flexible and convenient.

Arduino Cloud even works in a mobile browser. Screenshot: Arduino Cloud / Skillbox Media
Platform IO in the Visual Studio Code editorScreenshot: Visual Studio Code / Skillbox Media

Platform IO is a powerful plugin that transforms a code editor like VS Code into a full-fledged integrated development environment (IDE) for working with Arduino. With Platform IO, users have access to tools for debugging, code analysis, and testing, and can also easily flash boards. This tool significantly simplifies the development process, increasing the efficiency of working with Arduino projects.

The plugin is free and available for most popular IDEs and code editors. There is also a version for Vim that runs in the terminal. This tool allows developers to effectively integrate functionality, which improves the process of writing and editing code.

Platform IO in the terminal Screenshot: Platform IO

Visual Studio Code: Installation, Configuration, Localization, and Hotkeys

Visual Studio Code is a powerful code editor that has become popular among developers due to its flexibility and many extensions. Installing Visual Studio Code is simple and is available for all major operating systems, including Windows, macOS, and Linux. To get started, download the installation file from the official Microsoft website and follow the installation instructions.

After installation, we recommend customizing the editor to suit your needs. In Visual Studio Code, you can customize themes, fonts, and other interface options. To improve your coding experience, you can install useful extensions, such as linters and tools for working with various programming languages. One important step in setting up the interface is localizing it. To localize Visual Studio Code, install the appropriate extension from the store, which will allow you to use the editor in Russian.

Keyboard shortcuts in Visual Studio Code significantly speed up the development process. Learning and using keyboard shortcuts, such as Ctrl + P for quick access to files or Ctrl + Shift + P to open the command palette, can significantly increase your productivity. Check out the list of keyboard shortcuts in the editor settings to optimize your work.

Using Visual Studio Code, you get a powerful development tool that can easily be adapted to your personal preferences and workflows.

How to Program Arduino

Code for Arduino is written in the Arduino C programming language, which is a combination of C++ and the Wiring framework. Developers call code files "sketch," which comes from the English word "sketch." This language offers simplicity and accessibility, making it ideal for both beginner and experienced embedded developers.

In this article, we'll discuss the basic concepts of programming on the Arduino platform. If your goal is to become an expert in development, we recommend bookmarking our extensive five-part guide to C++.

  • C++ for Beginners - What is this programming language, how to write programs: Part 1 of the guide
  • Variables, constants in C++ and operations with them: Part 2 of the programming language guide
  • If-else in C++, branching and logical operations: Part 3 of the programming language guide
  • Data input and exception handling in C++: Part 4 of the programming language guide
  • Functions, procedures, recursion in C++: Part 5 of the programming language guide

Programming for Arduino follows a specific pattern that includes the basic elements for creating functional code. This pattern typically consists of two key parts: the setup() and loop() functions. The setup() function initializes all the necessary parameters and settings, such as setting the pin modes or configuring the serial connection. The loop() function executes the main code, which will repeat indefinitely, allowing the device to respond to changes and perform tasks in real time.

To optimize your code and make it more efficient, it is important to follow these principles: structuring the code to improve readability, using comments to explain the logic, and avoiding redundant operations. Proper code formatting and organization will not only make it easier to maintain but also speed up the development process.

Therefore, following the Arduino programming pattern is a key aspect of successfully creating projects and developing software for microcontrollers.

This document contains information on various aspects of the topic. Key points are discussed that will help you gain a deeper understanding of the subject and its importance. It also focuses on the main factors influencing the development of this topic, allowing readers to gain a complete understanding and up-to-date data. The text is prepared with SEO in mind to ensure maximum visibility in search engines and attract the target audience.

  • #include — a directive for including third-party libraries or linking multiple files of a single project.
  • void setup() — a function in which the board pins are initialized and their operating modes are specified.
  • void loop() — a loop with the main program code. In it, developers describe the firmware logic and use the pins that were initialized in the setup() function.

The setup and loop functions are integral components of every Arduino sketch. Without their presence, the compiler will not be able to successfully build the project. The setup function is responsible for the initial configuration and is executed only once at device startup, while the loop function ensures continuous code execution, which allows the program to respond to changes in the environment. Proper use of these functions is critical to the successful operation of the project.

In Arduino C, as in other programming languages, variables play an important role. They allow you to store data received from sensors, perform intermediate calculations, and set pin parameters. The most commonly used variable types include integers, floating-point numbers, Booleans, and symbols. Choosing the right variable type is important for optimizing memory usage and improving code performance. Understanding the different variable types and their properties is a key aspect of effective Arduino programming.

  • int — integers ranging from -32768 to 32767.
  • long — integers ranging from -2147483648 to 2147483647.
  • float — floating-point numbers that can store values ​​with up to seven decimal places.
  • byte — individual characters from the ASCII table.
  • String() — multi-character strings.
  • bool — logical values ​​true or false.

The Arduino C programming language provides all the standard mathematical operators. Using them, you can perform calculations and assign the resulting values ​​to variables. This allows you to create effective and functional programs for various projects on the Arduino platform. Использование математических операторов, таких как сложение, вычитание, умножение и деление, является основой для выполнения арифметических операций и обработки данных в вашем коде.

Операторы сравнения предназначены для сравнения значений и возвращают результат в виде логического значения: true (истина) или false (ложь). Эти операторы играют ключевую роль в программировании, позволяя разработчикам проверять условия и принимать решения на основе этих проверок. Основные операторы сравнения включают равенство, неравенство, больше и меньше, а также их комбинации. Правильное использование операторов сравнения обеспечивает более эффективную логику в коде и упрощает анализ данных.

В языке программирования Arduino C для управления потоками выполнения программы используются условные операторы и циклы. Эти конструкции позволяют разработчикам принимать решения на основе определенных условий и повторять действия, что делает код более гибким и эффективным. Условные операторы, такие как if, else if и else, позволяют выполнять различные блоки кода в зависимости от истинности заданных условий. Циклы, включая for, while и do while, обеспечивают повторное выполнение блока кода до тех пор, пока выполняется заданное условие. Использование этих элементов управления потоком значительно упрощает процесс разработки и позволяет создавать более сложные и функциональные проекты на платформе Arduino.

  • if-else is an "if" statement that allows you to implement multiple scenarios and run them based on conditions. If the if statement's condition is met, the system executes it. Otherwise, the else if condition is executed.
  • for is a loop for repeatedly performing the same action. For example, you can use it to loop through an array of LEDs and blink each one.
  • while is a loop that runs as long as its condition is true.
  • do-while is a loop that first performs an action and then checks the termination condition.

To make a program more convenient to use, it is advisable to divide it into functions - these are blocks of code that perform specific actions, return results, and are accessible from any part of the program. Let's consider an example: you are developing a laser device for measuring distance. The sensor transmits values ​​​​in meters, but you also need to display the results in kilometers and feet. In this case, value conversion operations can be moved to a separate function, allowing it to be called anywhere in the code. This approach not only simplifies the program structure but also makes it more readable and easier to modify.

Functions in Arduino are an important programming element, allowing you to organize your code and improve its readability. In general, functions in Arduino have the following syntax:

return_type function_name(parameters) {
// function body
}

The return type specifies what type of data the function will return, for example, int, float, or void if the function returns nothing. The function name must be unique and describe its purpose. Parameters passed to the function allow it to be used with different input data.

Functions help structure your code, making it more modular and easier to debug. Using functions in Arduino allows for code reuse, saving time and effort when developing projects.

In this article, we'll cover the main aspects of this topic. We'll discuss key points and provide helpful tips and tricks to help you better understand the subject. We'll also address relevant questions and answer frequently asked questions to ensure a thorough understanding. It is important to note that the information will be presented in an accessible and understandable form so that each reader can get the most out of it.

  • return_type — the data type that the function returns as a result of its operation;
  • function_name — the name by which the function can be called;
  • arguments — the variables that the function receives as input;
  • function_body — the main code of the function.
  • return_value — the value that the function will return after execution.

Let's consider a function that takes two numeric values, calculates their sum, and displays information to the console whether the sum is even or odd. This function will help you better understand the basics of working with numbers in programming and conditional operators.

The function takes two parameters, adds them together, and checks the result for parity. If the sum is even, a corresponding message is displayed; if it is odd, the same is true. This is a simple yet effective way to demonstrate basic algorithms and programming logic.

How to Upload Firmware to the Board

Before you start writing code, it's important to understand how to upload code to the board. Uploading code to the board is a key step in project development, as it allows your software to interact with the device's hardware. Make sure you have the necessary software and drivers installed. Then, connect the board to your computer using a USB cable. Use the appropriate development environment to upload your code, selecting the correct board and port. Once the upload is complete, you can test the functionality of your project, which is an important step in the development process.

  • Step 1. Connect the board to your computer using a USB cable.
  • Step 2. In the Arduino IDE, open the Select board drop-down list and select your board.
Screenshot: Arduino IDE / Skillbox Media
  • Step 3. Click on the arrow button to the left of the drop-down list.
Screenshot: Arduino IDE / Skillbox Media
  • Step 4. If everything went well, the terminal will display the message "Done uploading" and information about how much memory the sketch has taken up.
Screenshot: Arduino IDE / Skillbox Media

Blinking the LED: the first project on Arduino

Many Developers begin their programming journey by creating a program that displays "Hello, world!" on the screen. However, microcontrollers lack screens, making this approach impossible. The developer community has its own version of this tradition: Blink, a program that controls the blinking of an LED on a board. This simple program not only demonstrates the basic principles of working with microcontrollers but also allows beginners to master basic programming skills and interact with hardware. Blink is an excellent starting point for learning how to work with microcontrollers and developing more complex projects. This simple program allows you to check three aspects at once. If the LED blinks, it indicates certain conditions or errors in the system. It is important to pay attention to the frequency and pattern of the blinking, as they can provide clues about what is happening. This program allows you to quickly diagnose problems and determine whether further intervention or repair is required. Understanding LED blinking accurately will help you effectively resolve any issues that arise.

  • The board is working correctly, and the electronic components are undamaged;
  • The compiler is configured correctly and compiles code for the target platform;
  • The computer uploads firmware to the board without errors.

Let's write a Blink program to upload to the Arduino and test it. This simple code will allow us to test the board's functionality and ensure that it correctly executes commands. Using the Blink program, we can make the LED on the board blink at a specified interval, which is a standard first project for Arduino users.

To implement the program, you need to open the Arduino IDE, create a new file and enter the following code:

«`cpp
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
digitalWrite(LED_BUILTIN, HIGH); // Turn on the LED
delay(1000); // Wait 1 second
digitalWrite(LED_BUILTIN, LOW); // Turn off the LED
delay(1000); // Wait 1 second
}
«`

Once you have written the code, upload it to your Arduino board. Make sure you select the correct port and board model in the IDE. After the program is uploaded, the LED should start blinking at one-second intervals. This project is a great start for learning the basics of Arduino and microcontroller programming.

To successfully build the project, you will need the following set of tools and materials.

  • Any Arduino board (we have Uno R3);
  • LED;
  • 220 ohm resistor;
  • Male-male wires;
  • Breadboard.

All components are connected as follows:

LED connection diagram to Arduino UnoInfographics: Skillbox Media
Photo: Skillbox Media

The code for blinking an LED is shown below. This simple example demonstrates how to control an LED using a microcontroller. This code uses the standard library, which makes it easy to integrate into any project.

«`cpp
#define LED_PIN 13 // Define the pin for the LED

void setup() {
pinMode(LED_PIN, OUTPUT); // Set the pin as output
}

void loop() {
digitalWrite(LED_PIN, HIGH); // Turn on the LED
delay(1000); // Wait 1 second
digitalWrite(LED_PIN, LOW); // Turn off the LED
delay(1000); // Wait for 1 second
}
«`

This code makes the LED blink with a period of one second. You can change the value in the delay() function to adjust the blinking frequency according to your needs. Use this example in your projects to create simple visual effects and indicators.

The given code uses three functions, in addition to the setup() and loop() functions, which are required for compiling the sketch. These functions play a crucial role in the operation of the program, ensuring that the necessary tasks are performed. Configuring the functions and their interaction with the main logic of the program help ensure efficient code execution and proper functioning of the device.

  • pinMode(pin, mode) — a function for setting the operating mode of a digital pin. It takes two arguments: pin and mode. The first one specifies the pin number, the second one specifies the operating mode. We've selected pin number 13 and made it an OUTPUT.
  • digitalWrite(pin, value) — a function for applying voltage to the pin specified in the pin argument. The second argument specifies the value to apply to the pin: HIGH or LOW.
  • delay() — this function allows you to pause code execution temporarily. To do this, specify the pause duration in milliseconds in parentheses. Fun fact: the maximum value is 4,294,967,295 ms, which is 49 days, but in practice, no one pauses for more than a few seconds :)

When power is properly connected to the board, the LED should start blinking. This indicates that all preliminary steps have been successfully completed. Make sure all connections are correct to avoid potential issues with the device.

Photo: Skillbox Media

Complicating the project: adding control

In this project, we will complicate the task by adding the ability to constantly light an LED, which will be controlled by a button. This way, the LED will automatically turn on and off at the press of a button. This solution not only improves the project's functionality but also makes it more user-friendly. Setting up such a circuit will require the use of additional components, such as resistors and transistors, to ensure reliable operation of the device.

The circuit diagram of the device is presented as follows:

Infographics: Skillbox Media

The result should be a device that effectively performs its functions. It should be reliable, durable and easy to use. It's important that the device's design ensures high performance and meets modern quality standards. Ergonomics and design must also be considered to ensure it's appealing to users. The device should have an intuitive interface and be affordable, which will attract a wide audience.

Photo: Skillbox Media

The project code is presented in the following format:

If all the steps were performed correctly, you will be able to control the LED using the button. This will allow you to easily turn the LED on and off, as well as control its brightness and operating modes. Make sure all connections are secure and test the system to ensure proper operation.

Photo: Skillbox Media

What's Next

If you've successfully completed the projects in this article and are looking for more challenging projects, we recommend checking out our guide on building a robot. In this guide, we explain in detail the process of constructing and programming a controlled mini-platform.

Learn more about our topic. We offer up-to-date information and useful tips to help you better understand the issue. Discover new aspects and deepen your knowledge by exploring additional materials and resources available on our website. Our goal is to provide you with quality content that is useful and informative. Don't miss the opportunity to expand your horizons.

Building a Robot from Scratch: A Detailed Guide

Building a robot from scratch is a fun process that combines elements of engineering, programming, and creativity. To successfully build a robot, you need to follow clear instructions that will help you bring your idea to life step by step.

The first step in building a robot is determining its purpose and functionality. Consider what tasks it should perform. This could be simple manipulation of objects, movement along a given path, or execution of complex algorithms. A clear understanding of your goals will help you select the necessary components.

The next step is selecting the necessary parts. Depending on the functions of your robot, you will need a microcontroller, motors, sensors, batteries, and other components. Pay attention to the compatibility of components and their characteristics to ensure stable operation of the device.

Once all the parts are ready, proceed to assembly. Start by creating the robot frame, then install the motors and sensors, following the wiring diagram. Make sure all components are securely fastened to avoid breakage during operation.

Once the mechanical part is assembled, you can move on to programming. Write the code that will control your robot. Use appropriate programming languages, such as C++, Python, or Scratch, depending on your skill level and the type of microcontroller used.

Once programming is complete, test the robot. Check that it performs the intended functions and, if necessary, make adjustments to the code or design. Don't be afraid to experiment—it's an important part of the process.

Building a robot from scratch is not only a technical process, but also a creative one. Success depends on your patience, attention to detail, and desire to learn. By following this instruction, you can create a unique robot that will become your personal project and a source of pride.

There are many open-source projects on the Arduino platform that you can easily replicate. These projects provide an excellent opportunity to learn the basics of programming and electronics, as well as get inspiration for creating your own unique devices. With a vibrant community of developers, you'll find a variety of examples, from simple circuits to complex systems, that will help you develop your skills and implement innovative ideas. Studying these projects will not only enrich your experience, but also allow you to contribute to the Arduino community.

  • ArduSat — a miniature space satellite;
  • Arduboy — a portable game console.
  • ArduPilot — an autopilot system for drones, airplanes, boats, and rovers.
  • OpenEVSE — a charging station for electric cars.

Additional Resources

We've put together a selection of videos, courses, and books to help you deepen your knowledge of Arduino programming. These resources are suitable for both beginners and more experienced users looking to improve their skills. Изучая представленные материалы, вы сможете освоить различные аспекты работы с Arduino, включая базовые концепции, проектирование схем и создание собственных проектов.

  • Arduino The Documentary — документальный фильм, в котором создатели платформы рассказывают о процессе разработки.
  • 10-часовой видеокурс по программированию Arduino от Free Code Camp.
  • Arduino Project Hub — платформа, на которой пользователи делятся своими проектами.
  • Arduino Docs — документация от команды создателей Arduino.
  • Официальные гайды — руководства по программированию плат.
  • «Изучаем Arduino. 65 проектов своими руками», Джон Бокселл. Книга с проектами, собирая которые вы научитесь программировать для Arduino.

Программист микроконтролле­ров

Вы научитесь писать код для устройств, которые управляют роботами, дронами и другой электроникой. Сможете начать карьеру в одной из самых перспективных сфер IT-индустрии.

Узнать подробнее