Raspberry pi arduino program

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.

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.



цифровая электроника вычислительная техника встраиваемые системы

Программируем 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.


Program an AVR or Arduino Using Raspberry Pi GPIO


New Subscription

Please sign in to subscribe to this guide.

You will be redirected back to this guide once you sign in, and can then subscribe to this guide.

This is a short guide to explain how to program an AVR microcontroller (like what powers an Arduino Uno) directly from the GPIO pins on a Raspberry Pi. Why would you want to program an AVR from a Pi? If you’re building up an AVR-based board or product from scratch you’ll need some way to program code onto the chip. Typically dedicated tools like the USBtinyISP are used to program an AVR through its in-circuit serial programming (ISP or ICSP) pins, however with the latest version of the avrdude programming tool you can actually use Linux GPIO pins to program an AVR directly—no dedicated programmer required! This guide will walk you through how to install and use avrdude to program an AVR microchip or Arduino through its ISP pins with a Raspberry Pi.

Note that this tutorial is somewhat advanced and targeted at people who are familiar with programming an AVR chip directly instead of using friendlier tools like the Arduino IDE. It will help to be familiar with setting up a breadboard Arduino and loading its bootloader through an ISP programmer. If you’re a beginner or new to Arduino, stick with using the Arduino IDE to program your board.

To follow this guide you’ll need the following hardware:

  • Raspberry Pi — Any model will work, but note that you need 4 GPIO pins free for each AVR that will be programmed at a time.
  • An AVR chip & development board or an Arduino board that exposes the ICSP pins (like an Arduino Uno).
  • Breadboard and wires to connect the ICSP pins of the AVR/Arduino to GPIO pins on the Raspberry Pi.


You’ll need to compile and install the latest version of the avrdude programming tool on the Raspberry Pi. These instructions assume you’re using a version of the Raspbian operating system and are familiar with how to connect to the terminal on the Raspberry Pi.

Also note these instructions were written for version 6.1 of avrdude, but has been verified to work with up to version 6.3. Earlier versions won’t work because they don’t have the required linuxgpio programmer type. Later versions might work, but they might require more dependencies or a different configuration.

If you just want to get up and running as fast as possible follow these steps to install the package. If you run into an issue or would like to compile the code yourself, skip down to the compile avrdude section.

Jun the following command to install or upgrade the avrdude package:

Answer yes to any question about installing packages, and after a moment the updated avrdude package should be installed. Skip down to the verify installation section to continue.

To manually compile avrdude follow the steps below. First run these commands to install some required dependencies:

Then download the source and configure avrdude for compilation by executing:

After the configure script runs verify that it shows the line «ENABLED linuxgpio» like below (you can safely ignore the DISABLED and DON’T HAVE warnings):

Now build and install avrdude by running:

Now that avrdude is compiled and installed you can verify the expected version 6.1 is installed. Run the avrdude -v command and check that you see output like the following with version 6.1:

Once avrdude 6.1 is compiled and installed, continue on to learn how to configure avrdude to program using the GPIO pins.


To program an AVR from the Pi you’ll need to have 4 GPIO pins free on the Raspberry Pi. These pins will connect to the AVR’s ISP/ICSP MOSI, MISO, SCK, and RESET pins. In addition you’ll connect the Pi’s 5 volt power and ground to the AVR to power it during programming.

If you’re using an Arduino Uno you can access all the required pins from the small ICSP header on the far end of the board.

As an example using an Arduino Uno here’s one possible way to connect it to a Raspberry Pi:

  • Arduino ICSP VCC to Raspberry Pi 3.3 volt pin. (You can also try 5V, which is riskier because there’s 5V logic coming out of the Arduino to the Pi but its not a ‘strong’ 5V signal, so if you do just put a 1K resistor in series with the MISO output between AVR and Pi or you could use a level shifter)
  • Arduino ICSP GND to Raspberry Pi ground pin.
  • Arduino ICSP RESET to Raspberry Pi GPIO #12.
  • Arduino ICSP SCK to Raspberry Pi GPIO #24.
  • Arduino ICSP MOSI to Raspberry Pi GPIO #23.
  • Arduino ICSP MISO to Raspberry Pi GPIO #18.

You’ll need to create a custom avrdude configuration file to tell avrdude what GPIO pins to use for programming the AVR. It’s easiest to copy the default avrdude.conf file and make the necessary changes to it.

The avrdude.conf file will be in one of two spots depending on how you installed avrdude in the previous section. If you did the easy install method to install through a package then avrdude.conf is in the /etc/avrdude.conf location. However if you did the manual install method to compile the code and install it then avrdude.conf is in the /usr/local/etc/avrdude.conf location.

Copy the avrdude.conf configuration to a new file called avrdude_gpio.conf in your home directory, and then edit it with the nano text editor by running the commands below. If you used the easy install method to install an avrdude package these commands are:

However if you used the manual install method to compile the code then instead run these commands:

Once in the editor scroll all the way down to the very end of the file. You’ll need to add a new section that configures the GPIO pin programming. Paste in the following section at the end of the file:

This configuration will create a programmer with name ‘pi_1’ and assign the ICSP pins to the provided GPIO pin values. If you’ve hooked up the ICSP pins to different GPIO pins make sure to modify the configuration to match your setup.

Also note that you can create mulitple programmer sections if you’re programming multiple AVR chips from the same Raspberry Pi. Each programmer section needs to have a unique name assigned with the id = «name» line. In addition each AVR needs a distinct set of 4 GPIO pins configured for its ICSP pins.

Once you’ve modified the configuration file save it and quit nano by pressing Ctrl-O, enter, and then Ctrl-X.

Continue on to learn how to use avrdude with the custom GPIO programming configuration.


Now you’re ready to program the AVR using the Pi’s GPIO pins! Make sure you’ve followed all the steps to this point and have compiled, installed, and configured avrdude for GPIO programming.

To program the chip you’ll need a .hex file that has the compiled code you wish to run. With the Arduino IDE installed on your computer, an easy way to generate this file is to turn on the verbose compile and upload output (under preferences). Configure Arduino for the board/chip you’re using and compile the code. In the debug output look for the line at the end that calls avr-objcopy to prepare the .hex file, for example compiling a Blink example on my machine produced the following:

The file /tmp/build6154610255332504576.tmp/Blink.cpp.hex is the output .hex file that can be written directly to the AVR/Arduino using avrdude. Grab the .hex file and copy it to your Raspberry Pi.

Another way to generate a .hex file is to setup your own avr-gcc toolchain and compile code for the desired chip. This can be a somewhat daunting process so I recommend using Arduino’s prebuilt toolchain. However if you’re going at it yourself take a look at the instructions on setting up avr-gcc here—good luck!

Now from the Raspberry Pi run an avrdude command to verify it can connect to the AVR chip:

Notice the chip type is specified with -p, the path to the custom avrdude.conf
is specified with -C, and the name of the programmer is specified with -c. If you’re using a different chip, configuration file path, or programmer name be sure to change the values.

Once the command runs you should see output like the following with avrdude reading the memory & fuses of the AVR chip:

If you see an error make sure you’re running the command as root with sudo. Also go back and ensure the custom avrdude configuration exists in the expected location, the configuration has the specified programmer, and the programmer configuration is using the GPIO pins you have connected to the AVR.

Also note if you receive an error that a GPIO pin is in use try changing that pin to use a different one in the programmer configuration.

Once you’ve verified avrdude can talk to the chip you’re ready to program it! You’ll need the .hex file that was compiled, then run a command like the following to program the chip:

Again the -p option configures the chip to program, the -C option points to your custom avrdude configuration, and the -c option specifies the custom programmer configuration block to use. The -U flash. option tells avrdude to wipe and program the flash memory of the AVR chip, and to use the provided Blink.cpp.hex file. Change the name and path to the hex file to the appropriate value for the code you’re writing to the chip.

If avrdude successfully programs the chip you should see output like the following:

Congratulations, you’ve successfully programmed an AVR chip using the GPIO pins on a Raspberry Pi!

If you program an Arduino board like the Uno using the method in this guide be aware that you might remove or overwrite the USB/serial bootloader. This can actually be useful if you need just a little more space in your sketch (the bootloader takes a few kilobytes of memory at the end of flash), however it means that you won’t be able to program the Arduino using the Arduino IDE’s normal USB/serial programming interface. Don’t worry though you can burn the original Arduino bootloader back on your Arduino board to have it work with the Arduino IDE again.

Check out this tutorial for information on burning an Arduino bootloader from a .hex file using avrdude. If you download the Arduino IDE look for a firmware .hex file in the hardware/arduino/avr/bootloaders/optiboot directory beneath the IDE’s installation. For an Arduino Uno the optiboot_atmega328.hex file is the bootloader file to use. Program this hex file to the Arduino using avrdude on the Raspberry Pi to restore the Arduino to its normal state and make programming work with the Arduino IDE again.

This guide was first published on Jun 01, 2015. It was last updated on Jun 01, 2015.