От Arduino к Arduino с использованием последовательного интерфейса
Обмен данными между двумя платами Arduino — очень полезная фича для многих проектов.
Например, можно чтобы одна плата Arduino управляла моторами, а вторая использовалась для подключения сенсоров и передачи управляющих сигналов на первый микроконтроллер. Реализовать обмен данными между двумя Arduino можно с использованием с помощью последовательного (serial) интерфейса. Для этого будут использоваться контакты RX и TX.
Схема подключения
На рисунке ниже показана схема подключения двух контроллеров Arduino. На схеме показаны две платы Arduino Uno, но можно использовать и Arduino Mega, если использовать соответствующие контакты RX и TX.

Обратите внимание, что необходимо объединить контакты Gnd.
В противном случае, обмен данными происходить не будет! При подключении контакт TX подключается к RX, а RX — к TX.
Особенности программы
При использовании серийного интерфейса, данные передаются в байтах. Эти байты считываются вторым Arduino по одному. Если мы передаем символы, преобразовать их в байты не проблема. Но если мы передаем и символы и цифровые значения, данные могут интерпретироваться некорректно, так как число и символ могут принимать одинаковые значения в байтах. Кроме того, числа могут не поместиться в один байт. Самое простое решение этой проблемы — не передавать символы и числа одновременно.
Простой скетч
Можно настроить передачу данных между двумя Arduino с использованием примера Physical Pixel.
Загрузите скетч Physical Pixel, который можно найти в Arduino IDE в папке: File >> Examples >> Communication, на ваш Arduino.
На вторую плату Arduino загрузите следующий скетч:
Когда код начинает работать, светодиод на 13 пине Arduino должен загораться и тухнуть с частотой 0.5 Гц. Для того, чтобы удостоверится в работоспособности скетча, можете изменить значение задержки (delay).
Символ ‘H’ в приведенном выше скетче зажигает светодиод, а символ ‘L’ отвечает за отключение светодиода. Можно расширить этот список символов для выполнения других действий.
Но этот код недостаточно гибкий и для решения более комплексных и сложных задач может не подойти.
Расширенный скетч
Есть второй вариант скетча для передачи данных от одного Arduino к другому. Для этого все данные с Arduino, который передает информацию, преобразовываются в символы. Вторая плата Arduino считывает поступающие данные тоже в символах. На практике данные, конечно, передаются в байтах, но наш Arduino отлично справляется с конвертацией символов в байты и обратно.
Скетч для Arduino, передающего данные
Скетч для микроконтроллера, который передает данные, конвертирует символы в байты и, если необходимо, преобразовывает числовые значения в символы, перед тем как превратить их в байты. Пример скетча приведен ниже.
// скетч для Arduino, который передает данные
int value=1234; // будет гораздо веселее, если это будут данные с какого-то сенсора
itoa(value, str, 10); // преобразует данные в массив символов
Скетч для Arduino, принимающего данные
Второй микроконтроллер Arduino получит массив данных в байтах и начнет их интерпретировать. Скетч для платы-ресивера приведен ниже.
Урок 26.1 Соединяем две arduino по шине UART

При создании некоторых проектов, требуется разделить выполняемые задачи между несколькими Arduino.
В этом уроке мы научимся соединять две Arduino по аппаратной шине UART.
Преимущества:
- Простота реализации.
- Дуплексная связь, обе Arduino могут одновременно передавать данные друг другу.
Недостатки:
- Нет возможности «залить» скетч, при наличии устройств на аппаратной шине UART.
- Реализуется соединение только двух устройств (при отсутствии доп. модулей).
Нам понадобится:
-
х 2шт.
- LCD дисплей LCD1602 IIC/I2C(синий) или LCD1602 IIC/I2C(зелёный) х 2шт. х 2шт. х 2шт. х 2шт.
- Шлейф «мама-мама» (3 провода) для шины UART x 1шт.
Для реализации проекта нам необходимо установить библиотеки:
- Библиотека iarduino_KB (для подключения матричных клавиатур).
- Библиотека LiquidCrystal_I2C_V112 (для подключения дисплеев LCD1602 по шине I2C).
О том как устанавливать библиотеки, Вы можете ознакомиться на странице Wiki — Установка библиотек в Arduino IDE .
Видео:
Схема подключения:
Подключение LCD дисплея осуществляется к аппаратным выводам шины I2C.
Клавиатура подключается к любым цифровым выводам, в примере используются выводы 2-9.
Соединение двух arduino осуществляется по шине UART:
| Arduino 1 | Arduino 2 |
|---|---|
| TX (transmit — передать) | RX (receive — получить) |
| RX (receive — получить) | TX (transmit — передать) |
| GND (ground — земля) | GND (ground — земля) |
Код программы:
Настройка параметров шины UART:
Максимальная, аппаратно реализуемая частота передачи данных, может достигать 1/8 от тактовой частоты.
Настройка шины осуществляется вызовом функции begin() класса Serial, с передачей ей до двух аргументов. Первый аргумент устанавливает частоту передачи данных (в примере 9600 бод), второй (необязательный) аргумент устанавливает количество битов, наличие проверки на четность/нечетность, длину стопового бита (по умолчанию SERIAL_8N1).
Допустимые значения второго аргумента функции begin() класса Serial:
- SERIAL_5N1
- SERIAL_6N1
- SERIAL_7N1
- SERIAL_8N1
- SERIAL_5N2
- SERIAL_6N2
- SERIAL_7N2
- SERIAL_8N2
- SERIAL_5E1
- SERIAL_6E1
- SERIAL_7E1
- SERIAL_8E1
- SERIAL_5E2
- SERIAL_6E2
- SERIAL_7E2
- SERIAL_8E2
- SERIAL_5O1
- SERIAL_6O1
- SERIAL_7O1
- SERIAL_8O1
- SERIAL_5O2
- SERIAL_6O2
- SERIAL_7O2
- SERIAL_8O2
Значения отличаются последними тремя символами, которые означают следующее:
- Первая цифра: указывает количество бит в минимальной посылке (от 5 до 8).
- Буква N/E/O: E-проверка четности, O-проверка нечетности, N-без проверки.
- Последняя цифра: указывает длину стопового бита (1 или 2 битовых интервала)
Таким образом значение по умолчанию SERIAL_8N1 означает, что в минимальной посылке 8 бит (без учёта стартового и стопового битов), данные передаются без проверки на чётность/нечётность, длина стопового бита равна 1 битовому интервалу.
Настройки шины UART обеих arduino должны быть идентичны!
Передача данных между микроконтроллерами Arduino через последовательный интерфейс

Обмен данными между двумя платами Arduino очень полезен. В больших проектах можно назначить несколько микроконтроллеров для управления техническими процессами.
Реализовать обмен данными между двумя микроконтроллерами Arduino можно с использованием последовательного интерфейса передачи данных. Для этого будут использоваться контакты RX-0 и TX-1.
Схема подключения микроконтроллеров Arduino UNO

Контакт Arduino UNO -1 RX-0 подключается к контакту TX-1 Arduino UNO -2 и на оборот контакт TX-1 Arduino UNO -1 подключается к контакту RX-0 Arduino UNO -2.
Обратите внимание, что необходимо обязательно подключить контакты GND. В противном случае обмен данными происходить не будет!
Код C++ для микроконтроллера Arduino UNO -1
Микроконтроллер Arduino UNO -1 будет отправлять целочисленные данные через последовательный интерфейс на микроконтроллер Arduino UNO -2.
Код C++ для микроконтроллера Arduino UNO -2
Микроконтроллер Arduino UNO -2 будет получать целочисленные данные через последовательный интерфейс от микроконтроллера Arduino UNO -1.
Результат работы в консоли микроконтроллера Arduino UNO -1

Результат работы в консоли микроконтроллера Arduino UNO -2

Более подробную инструкцию вы можете получить посмотрев видео «Связь между двумя платами Arduino».
Connecting Two Nano Every Boards Through UART
In this tutorial we will control the built-in LED on the Arduino Nano Every from another Arduino Nano Every. To do so, we will connect both boards using a wired communication protocol called UART.
Note: This example would work connecting an Arduino Nano board with any other Arduino board, but be mindful that both board must work at the same voltage. If the operating voltage differ between connected boards, the board with the lower operating voltage could be damaged.
In this example, we will power both the Arduino boards through the computer, then we will use the Serial Monitor to send some commands to the Nano Every board, that will be connected through the UART with another Nano Every board. Depending on the commands received by the Nano Every board, it will turn ON or OFF its built-in LED.
Goals
The goals of this project are:
- Understand what the UART is.
- Use UART communication between two Arduino boards.
Hardware & Software Needed
For this project we will need:
- Arduino Nano Every
- Arduino Nano Every (or any other Arduino board that works at 5V)
- 2 x mini breadboard
- 3 x jumper wires
UART Communication
UART (Universal Asynchronous Receiver-Transmitter) is one of the most used device-to-device communication protocols. It allows an asynchronous serial communication in which the data format and transmission speed are configurable. The UART communication sends data bits one by one, from the least significant to the most significant, framed by start and stop bits so that precise timing is handled by the communication channel.
Embedded systems, microcontrollers, and computers mostly use UART as a form of device-to-device hardware protocol. Among the available communication protocols, UART uses only two wires for its transmitting and receiving ends, TX (Transmitter) and RX (Receiver). These pins are dedicated for that specific purpose, either transmitting or receiving.
Asynchronous means there is no clock signal to synchronize the output bits from the transmitting device going to the receiving end, but the baud rate needs to be the same on both the transmitting and receiving devices. The baud rate, is the rate at which information is transferred to a communication channel. In the serial port context, the set baud rate will serve as the maximum number of bits per second to be transferred.
UART is the communication protocol we use to communicate the PC to the board through the USB cable. In some older boards, TX and RX pins are used for communication with the computer, which means connecting anything to these pins can interfere with that communication, including causing failed uploads to the board. This is not the case for the Nano or MKR families, since these ones have two separate channels, using Serial for the communication with the computer and Serial1 for the communication with any other device through UART.
If you want to learn more about the UART protocol and how it works, you can check this link.
Circuit
In order to communicate both Arduino boards, we will need to connect them as shown in the image below.

The circuit.
At the moment of making the connections, we need to remember that this protocol has two dedicated lines TX and RX so we need to make sure to connect the TX pin, of one of the boards, with the RX of the other one. The same goes for the second, where his TX pin need to be connected to the RX pin of the first board.
To finish, it is very important that we connect the GND pins of both boards to each other. If we don't do this, the voltage reference will be different for each one of the boards so the communication won't work as intended.
Note: In order to enable serial communication, both Arduino boards must be connected to your computer via USB.
Creating the Program
1. Configuring the Receiver board
First, let's connect the Arduino Nano Every board to the computer and opening the Arduino Web Editor. This board will act as the receiver, which means that it will only receive data from the other board and turn ON or OFF the built-in LED according the received values. To start with the programming, start a new sketch and name it Nano_UART_receiver.
1.1. Receiver code walkthrough
Let's start inside the function. We need to initialize the built-in LED as and then turn it off. Then, we need to initialize the UART communication with the other board using the function.
Note: If you want to initialize the UART communication with any other Arduino board, please check here the serial port and the pins you need to use.
Inside the , we need to check if there is any byte available on the buffer using the function inside a statement. This configuration will run the portion of code inside the brackets of the only if there is any byte available to be read on the buffer of the UART1. If it is the case, we will read and store the available data in the variable using the function, since we want to read the data coming from the other Arduino board.
Now, we need to add a statement to check if the received data is or in order to turn on or off the built in LED respectively.
Note: When we use UART communication, all the data transmitted is text formatted, which means that we need to use character logic instead of numeric logic for compatibility. For example, in order to know if the data received is a "5" we need to check with the ASCII character of 5 ('5') instead of the numeric value of 5 (5). Therefore, we use dataReceived == '5' instead of dataReceived == 5.
1.2. Uploading the code to the receiver
Once we have finished the code, let's upload it to our Arduino Nano Every board. This board is now programmed to act as the receiver in this scenario. Once the code is uploaded, let's connect the other board to the computer.
Note: After uploading the code to the receiver board, it is not necessary for it to stay connected to the computer in order to function. However, it needs to be powered in order to work.
2. Configuring the Transmitter board
It is time to open a new sketch and name it as Nano_UART_transmitter, then let's start initializing the built in LED and the Serial communication as we did in the previous code but in this case since we need to read data also from the Serial Monitor we need to initialize the serial communication with the computer adding a function.
In the , we will use an statement to check if the data read from the Serial Monitor is equal to . If it is, we will use the function to send the same data to the other board. At the same time, we will turn on the built in LED of this board and print out a message in the Serial Monitor showing the state of the LED using the and functions respectively.
Then, using an statement, we need to do the same but in this case, if the data read from the Serial Monitor is equal to , we will turn the LED off.
2.1 Uploading the code to the transmitter
Once we have finished the code, let's upload it to our other Arduino Nano Every board. This board is now programmed to act as the transmitter.
3. Complete code
If you choose to skip the code building section, the complete code for both the receiver and the transmitter can be found below:
Receiver:
Transmitter:
Testing It Out
After you have successfully verified and uploaded the sketch to the two boards, make sure the transmitter board is connected and open the Serial Monitor. You need to enter a 1 to turn ON both LEDs, or a 0 to turn them OFF.

Serial Monitor output.
Troubleshoot
Sometimes errors occur, if the code is not working there are some common issues we can troubleshoot:
- Missing a bracket or a semicolon.
- Arduino board connected to the wrong port.
- Connection between the Arduino boards are not correct.
- Accidental interruption of cable connection.
Conclusion
In this simple tutorial we learned how to connect two Arduino boards so that they can communicate using UART communication.