Digitrode
цифровая электроника вычислительная техника встраиваемые системы
Программируем Arduino на Raspberry Pi
Плата Arduino и миникомпьютер Raspberry Pi являются, пожалуй, одними из самых популярных средств разработки у энтузиастов в области электроники и радиолюбителей всех мастей. Они стоят недорого и достаточно просты в использовании, причем настолько, что даже самый зеленый новичок сможет разобраться с принципами их работы, не затратив на это слишком много времени. Все это обеспечивается не только простотой применения, но и большим количеством документации и примеров, которые можно найти на просторах сети интернет. Плюс к этому имеется очень мощная поддержка со стороны радиолюбительского сообщества, которое постоянно расширяется. Одним из первых вопросов, который появляется у новичка, является вопрос о программировании аппаратного средства. Среда разработки Arduino IDE предоставляет очень простые возможности для программирования плат Arduino. Но Arduino можно программировать не только через персональный компьютер с установленной Arduino IDE, но и с помощью Raspberry Pi. Ведь Raspberry Pi это же тоже компьютер, и на него тоже можно поставить среду Arduino IDE. И это будет полезно не только новичкам, но и заядлым электронщикам.
Итак, как мы выяснили, программировать платы Arduino можно не только с помощью компьютера или ноутбука, но и с помощью Raspberry Pi. И в данном материале будет показано, как это сделать.
Перед выполнением всех приведенных ниже действий вы должны удостовериться, что на вашем Raspberry Pi настроено интернет-соединение и оно исправно функционирует.
Шаг 1: загрузитесь и залогинитесь
Итак, первым делом загрузите ваш миникомпьютер Raspberry Pi и введите свой логин и пароль к нему.
Шаг 2: перейдите в терминал
Перейдите в терминал LX на Raspberry Pi напечатайте строку, показанную ниже.
Шаг 3: введите строку загрузки Arduino IDE
В терминале введите следующую строку:
sudo apt-get install arduino
Нажмите клавишу Enter. Теперь остается только подождать окончания загрузки.
Шаг 4: поместите иконку Arduino IDE на рабочий стол
Нажмите на кнопку меню в левом нижнем углу. Найдите иконку Arduino IDE, нажмите на нее правой кнопкой мыши и выберите Add to desktop.
Шаг 5: откройте IDE и загрузите скетч
Запустите Arduino IDE и откройте необходимый вам скетч. Можно взять скетч из папки примеров (fade или blink). Нажмите на иконку со стрелкой и загрузите скетч. Предварительно плата Arduino должна быть соединена с Raspberry Pi через USB.
Всё! теперь вы смело можете программировать любую плату Arduino с помощью своего миниПК Raspberry Pi.
Программируем Arduino с помощью Raspberry Pi
Статья о том,как при помощи GPIO прошить Arduino или совместимый с Arduino AVR.
Внимание!Все действия вы производите на свой страх и риск.Автор ответственности не несет.
Это руководство ориентировано на людях знакомых с ISP программированием или имеющим опыт работы с Arduino .Если вы не уверены в своих силах,то лучше использовать Arduino IDE.
- Raspberry Pi ,но учтите , что вам нужно 4 свободных GPIO порта для каждого AVR
- AVR чип или платы Arduino , который с гребенкой ICSP (например Arduino Uno).
- Макетная плата и провода для соединения выводов ICSP на AVR / Arduino и GPIO контактов на Raspberry Pi
Шаг 0.Добавим репозиторий из которого будем загружать ПО.
И добавим в открывшийся файл строку
Теперь в файле должно быть прописано два репозитория
2)Репозиторий Adafruit который мы сейчас добавили
Сохраняем файл и ставим avrdude
Для того,чтобы удостовериться,что все установилось
Шаг 1.Подключаемся.
Соединим контакты GPIO и ICSP контакты AVR/Arduino по схеме
- Arduino ICSP VCC к Raspberry Pi 5V pin.
- Arduino ICSP GND к Raspberry Pi GND pin.
- Arduino ICSP RESET к Raspberry Pi GPIO #12.
- Arduino ICSP SCK к Raspberry Pi GPIO #24.
- Arduino ICSP MOSI к Raspberry Pi GPIO #23.
- Arduino ICSP MISO к Raspberry Pi GPIO #18.
Шаг 2.Настроим AVRDUDE
И в конец файла добавим
Шаг 3.Программирование
Для начала нам нужно получить .hex файл скетча
Одним из способов его получения это скомпилировать скетч через ARDUINO IDE и посмотреть на наличие строки,которая укажет путь к .hex файлу
Удобнее всего это делать с ПК.
Также .hex файл можно получить через AVR GCC
Проверим доступность Arduino/AVR
Вывод должен быть примерно таким
Если все удачно,то мы готовы к прошивке
Где atmega328p модель контроллера,который прошиваем
Где Blink.cpp.hex необходимо указать путь и название .hex файла для прошивки
В моем случае вывод был таким
Такой вывод обозначает,что все прошито удачно.
Теперь удалим репозиторий
И уберем оттуда репозиторий ,который добавили в начале статьи.
Program an Arduino UNO with your Raspberry Pi
By Russell Barnes. Posted about 5 years ago.
In this feature we look at to connect an Arduino UNO to a Raspberry Pi and program Arduino IDE in Raspbian. We’re using an Arduino UNO with a Raspberry Pi 3 for this guide, but the steps are similar for all models.
The MagPi issue 122 out now
Discover retro gaming with Raspberry Pi Pico W in the latest edition of The MagPi magazine. Hack hardware, build handheld consoles and 1980s-style computers.
Install Arduino IDE on your Raspberry Pi
The first step in programming an Arduino board with a Raspberry Pi is to install the Arduino IDE (integrated development environment) on your Raspberry Pi. This program checks code and loads it onto the Arduino. Install the latest version of Arduino IDE using apt:
Alternatively, open Chrome on your Raspberry Pi, head to magpi.cc/2tPw8ht, and click the Linux ARM link under ‘Download the IDE’. Extract the file to your /opt directory , then open a Terminal and run the install.sh script to install.
You will find Arduino IDE under Menu > Programming. Open the app to start programming your Arduino board.
Program Arduino IDE on a Raspberry Pi
Arduino programs are called ‘sketches’, and are based on the C programming language. Open the IDE and you’ll see a blank sketch, with the two basic areas for code: void setup() and void loop(). If you see an empty script, choose File > Examples > 01.Basics > BareMinimum.
As the comments explain, void setup() is for code that runs once to set up your electronics properly. The code you type into void loop() will repeat from the first line to the last in an endless loop.
To demonstrate, we’ve written a basic sketch that flashes two LEDs when you move your hand over a PIR sensor. Connect the two LEDs and PIR sensor to the Arduino, as shown in the circuit diagram.
Once you’ve wired up the Arduino to the circuit, attach it to one of the Pi’s USB ports. This provides power to the Arduino, as well as a data connection between your Raspberry Pi and the Arduino board. Do not use the Arduino’s barrel-jack power input – a Pi 2 or 3 can supply enough power for an Arduino board over USB.
Blink a PIR with Arduino IDE
Enter the code from PIRBlink.ino and save it as PIRBlink using File > Save. It will be saved inside the Arduino directory in your home directory.
We use the pinMode instruction to tell the Arduino which GPIO pins the LEDs are attached to (pins 5 and 6) and that each pin should be treated as an output.
In the void loop() section, we tell the Arduino to raise the voltage on these pins to HIGH (5 V) with the digitalWrite instruction, then to pause for half a second, and then to turn off the LEDs.
Before uploading your sketch to the Arduino, tell the IDE which Arduino board you’re using by opening Tools > Board. Then tell the IDE which port to use to upload your code by opening Tools > Serial Port and selecting /dev/ttyACM0. On version 1.8.3 of the IDE, you need to select the version marked ‘(Arduino/Genuino Uno)’.
Now click Upload to program the Arduino with your sketch. After a few seconds of code-checking and uploading, you should see your LEDs flashing whenever you move your hand over the sensor.
Stop the program
Unlike a Raspberry Pi, the Arduino will keep running the same program, even if you unplug or reset the board. The easiest way to stop it running is to open a new blank program and upload it to the board.
Arduino IDE etiquette
While not necessary, it’s also good Arduino sketch etiquette to include a description at the start.
At the top of your sketch, type /* and hit ENTER: the IDE will add two more lines. Anything written between the /* and */ will be ignored by the Arduino, but can be read by any humans wanting to understand what your sketch does and how it works.
We’ve used variables for our LEDs, meaning that if we change the GPIO pins they’re attached to, we’ll have fewer edits to make.
We tell the Arduino IDE the type of variable, then the name, and the value. So our LED pins are int led1=5;. By replacing all instances of 5 with led1, any changes to our build require only one change to our code.
Add motion
We’ve also added a PIR (passive infrared) motion sensor, as shown in the circuit diagram (Figure 1). We therefore declared the variable int motion = 3 and added this line to void setup():
Finally, we added some code to make the motion sensor trigger the LED flashes:
As with the if statement, this is part of the void loop() section that will run continuously, meaning the motion sensor will be read – or polled – repeatedly for signs of motion.
A final note on coding with Arduino: every line of code must end with either a semicolon or a curly bracket. The IDE will highlight any line of code that suffers an error, and typically it’ll be because the previous line lacks its semicolon terminator.
If you are unfamiliar with the C programming language, there are lots of resources you can find online to learn how to use it.
Learn to Code with C
Arduino uses the C programming language. To get up to speed with C, read our Essentials Guide: Learn to Code with C.
How to Run Arduino Sketches on Raspberry Pi
Originally published by Feb 21, 2018
Table of Contents
Introduction
Raspberry Pi is an amazing minicomputer, and I would love to use it in some projects. There is just one tiny problem. I have little to no experience with Python. I used to do some Python coding a few years ago but only the basics. I’m more experienced in C++, specifically writing programs for Arduino. Wouldn’t it be nice if there was some way for those of us to utilize our Arduino programming skills on Raspberry Pi? Luckily, there is!
In this article, you will learn how to run sketches written for Arduino on Raspberry Pi! To achieve this, we will use RasPiArduino framework. That will allow us to compile the Arduino code into binaries which can run on Raspberry Pi. But before we can do that, we have to prepare a few things, both in the Arduino IDE and on Raspberry Pi.
Equipment
- Raspberry Pi 3 Model B
How to Run Arduino Sketches: Arduino IDE Setup
1. Open Arduino installation folder. On Windows systems, this will most likely be “C:\Program Files\Arduino” on 32-bit system or “C:\Program Files(x86)\Arduino” on 64-bit system.
Figure 1. Arduino installation folder
2. Open the folder “hardware” and create a new folder named “RaspberryPi” in this folder.
Figure 2. The newly created folder
3. Go to https://github.com/me-no-dev/RasPiArduino and clone the repository into a new folder “piduino” inside “RaspberryPi”. If you don’t want to clone the repository, you can download the repository content as a zip file and unzip it into the “piduino” folder.
Figure 3. The content of “piduino” folder
4. Next, you have to download GNU Toolchain from http://gnutoolchains.com/raspberry/ . You have to download the version that supports the version of your Raspberry OS. Since you probably use the latest Raspbian Stretch, you will want to download GCC 6.3.0. Once the file is downloaded, run it. Leave the installation path at “C:\SysGCC\raspberry”, check you accept the license agreement and click the button “Install”. After a while, the installation should complete successfully.
Figure 4. GNU Toolchain installer
5. Inside the Arduino installation directory, go to the “piduino“ folder we created in step 3. Open the file “platform.txt” and change the line number 5 from
runtime.tools.toolchain.path=
to
runtime.tools.toolchain.path=C:/SysGCC/Raspberry
This will point the compiler to the directory that contains the toolchain we installed in step 4.
Figure 5. Contents of platform.txt
6. Restart Arduino IDE and open a new sketch. In the “Tools” menu, under the “Board” option, there should now be a new board called “RaspberryPI B+/2”. To make sure everything is installed correctly, select the Raspberry Pi board, copy the code below and compile the sketch. The compilation might take longer than for Arduino boards and generate some warnings, but as long as it says “Done compiling” at the end, it should be fine.
Figure 6. Raspberry Pi board in Arduino IDE