Raspberry Pi to Arduino Serial USB Communication

RimstarOrg www.youtube.com

Краткое содержание

В этом видео рассказывается о том, как установить двустороннюю последовательную связь между Raspberry Pi и Arduino. Автор объясняет, как использовал Arduino в качестве контроллера двигателя для камер слежения и столкнулся с трудностями при организации двусторонней связи. Ключевым моментом стало добавление задержки и повторной установки DTR (Data Terminal Ready) после очистки, что позволило решить проблему.

  • Установка двусторонней последовательной связи между Raspberry Pi и Arduino может быть сложной задачей.
  • Добавление задержки и повторная установка DTR после очистки может решить проблему связи.
  • Код, представленный в видео, можно использовать на других платформах, таких как NVIDIA Jetson TX1.

Введение

Автор рассказывает о своем проекте, в котором он использует Arduino в качестве контроллера двигателей для камер слежения, а Raspberry Pi для обработки данных. Для связи между ними он использует последовательный порт через USB. Он отмечает, что столкнулся с трудностями при организации двусторонней связи и решил поделиться решением, которое ему помогло.

Физическое подключение и код Arduino

Подключение Raspberry Pi к Arduino (в данном случае Arduino Mega 2560) осуществляется с помощью обычного USB-кабеля. Автор демонстрирует код для Arduino, который включает в себя настройку скорости передачи данных (baud rate) и ожидание подключения к последовательному порту. В основном цикле (loop) код проверяет наличие данных в последовательном порту. Если получен символ "0", светодиод перестает мигать, и в ответ отправляется символ "A". Если получен символ "1", светодиод начинает мигать, и также отправляется символ "A". В случае получения любого другого символа отправляется символ "E" (ошибка).

Код Raspberry Pi на C

Автор показывает код на C для Raspberry Pi. Функция OpenSerialPort открывает последовательный порт и настраивает его параметры. В основном цикле программы отправляется символ "1" на Arduino, чтобы запустить мигание светодиода. Затем вызывается функция readFromSerial, которая ожидает ответа от Arduino (символ "A"). Полученный символ выводится на экран. Этот процесс повторяется с отправкой символа "0" для остановки мигания. Изначально этот код не работал.

Решение проблемы с DTR

Автор рассказывает, что после долгого времени поисков он нашел решение на hackaday.io в проекте четырехногого робота. Он заметил, что автор проекта успешно отправляет и получает данные между Arduino Mega 2560 и Raspberry Pi. Изучив код на Python, он обнаружил, что после очистки DTR (Data Terminal Ready) делается задержка в одну секунду, а затем DTR снова устанавливается. В своем исходном коде автор только очищал DTR. Добавление задержки и повторной установки DTR решило проблему, и светодиод начал мигать.

Код Raspberry Pi на Python и Jetson TX1

Автор переписал код на Python и столкнулся с той же проблемой: без задержки и повторной установки DTR код не работал. После добавления этих строк код заработал. Автор предоставляет ссылки на проект на Hackaday и на свой код в описании видео. Он также протестировал этот код на NVIDIA Jetson TX1 и успешно использовал его для связи с Arduino, который выступает в качестве контроллера сервоприводов.

Summarize any YouTube video in seconds

Get summaries like this one for any video, in your language, with the free Summ app.

Download on the Apple Store
Get it on Google Play

Расшифровка

YouTube Transcript Generator

0:00 Hi gang! I'm going to show you how I got two-way serial communication to work between a Raspberry Pi and an Arduino. I'm using the Arduino as a motor controller for two eye cameras, but I need something more powerful like a Raspberry Pi for the brains. I used serial over a USB cable so that I can use a PC or anything else if needed for more computing power. For example, the same code works on my NVIDIA Jetson TX1. However, the two-way communication turned out to be tricky to get working and held me back a while. So I thought I'd pass on to you what finally worked. Physically connecting the Raspberry Pi to the Arduino, in my case an Arduino Mega 2560, is easy. Just use the USB cable that comes with the Arduino and is normally used for programming it. I've tested with the Arduino's onboard

0:46 LED. I first wrote some code for the Arduino side. For the setup, I set the baud rate and wait for the serial port to connect. Then for the loop, I check if I've received any serial data. And if I did, then I read one byte of the data. If it's the character 0, then I stop the LED from blinking and send back a letter A over the serial port as an acknowledgement. That's not necessary, but it's good for testing the communication. If instead the character I received was a 1, then I start the LED blinking and also send back a letter A. For any other character, I send back an E, meaning error, since I'm not expecting any other characters. If instead I didn't receive any new serial data, then I just keep the LED blinking. Next came writing some code for the Raspberry Pi. I wrote it in C, and as you'll see later, I tried Python too. Here

1:31 in main, I call OpenSerialPort. It's this function here, which does the open, followed by a bunch of code to set up the serial port. I won't bore you with the details. Then back in main, I next go into an infinite while loop and write the character 1 to the serial port, the one that tells the Arduino to start blinking the LED. Then, to get the acknowledgement that my Arduino code sends back, I call readFromSerial, which is this function here. It simply goes into a loop, reading from the serial port. If the Arduino hasn't sent anything back yet, then it tries again. Remember, my Arduino code sends back an A, so this eventually gets it and returns to main, where I print out the A. I then do that all again, but this time starting with sending the zero character to the Arduino, to tell it to stop blinking. These steps keep repeating every two seconds forever. But it

2:21 didn't work very well. It just sat there. I was stuck for a few months. One day, I stumbled on the solution. I was looking at a project for a four-legged robot on hackaday.io and noticed he was sending successfully in both directions, between an Arduino Mega 2560 and a Raspberry Pi, just like me, but his was working. Looking at his Python code, I realized he was doing an extra step. After clearing DTR, he sleeps for one second and then sets DTR again. Looking back at my open serial port function, I was only clearing DTR. So I added a sleep and set DTR. This time my code worked. The LED started blinking. I decided to see if I had the same problem and solution with Python. So I wrote this code. And without the sleep and setting DTR again, it also didn't work. But after adding the

3:07 extra code, it did work. You can find a link to the Hackaday project in the video description, as well as a link to where you can find the code I've been showing you in this video. I also tried this code on my NVIDIA Jetson TX1 board and am now able to use it to communicate with the Arduino, using the Arduino as a servo motor controller.

Share

Краткое содержание видео YouTube