Guides · 9 min read

Arduino CLI Tutorial: Compile and Upload from the Command Line

Arduino CLI tutorial: install it, add cores and libraries, compile and upload, ESP32 and Pico FQBNs, a bulk upload script and VS Code tasks in one guide.

Arduino CLI is Arduino's official command-line tool: it compiles your code and uploads it to the board with a single command, without opening the Arduino IDE. Arduino IDE 2 actually runs the same engine in the background, so a sketch compiled with the CLI produces exactly the same file as one compiled in the IDE. The difference is that you type and repeat steps instead of clicking through them. If you want to flash the same code to ten boards, compile automatically on every save or upload from VS Code with one key, you are in the right place.

In this guide you will install Arduino CLI on Windows, macOS and Linux, add cores (board packages) and libraries, and learn the compile and upload commands with their flags. Then you will add ESP32 and Raspberry Pi Pico boards, flash several boards at once with a Python script, set up VS Code tasks and make the CLI share the same libraries as the IDE. At the end you will find fixes for the most common error messages.

What is Arduino CLI and how is it different from the IDE?

Arduino CLI is a single executable written in Go; it needs no installer, no Java and no Electron. It downloads board packages, calls the compiler (such as avr-gcc or xtensa-gcc), finds libraries and runs the upload tool (avrdude, esptool, picotool) with the right settings. The command-line equivalent of the board you pick from the IDE menu is the FQBN (Fully Qualified Board Name). An FQBN has three parts: vendor, architecture and board. For an Arduino Uno you write arduino:avr:uno, for a classic ESP32 esp32:esp32:esp32. Menu options such as the partition scheme or upload speed are added as a fourth part at the end of the FQBN.

FeatureArduino IDE 2Arduino CLI
UseMenus and buttonsTyped commands
SizeAbout 500 MBAbout 30–40 MB
AutomationNoneScripts, Makefile, CI, VS Code tasks
Needs a desktop?YesNo, it even runs over SSH on a Raspberry Pi
Serial monitor and plotterYesText monitor only (monitor)
Build outputIdenticalIdentical

Installation on Windows, macOS and Linux

SystemMethodNote
macOSbrew install arduino-cliEasiest way, update with brew upgrade
Linuxcurl -fsSL https://raw.githubusercontent.com/arduino/arduino-cli/master/install.sh | shPuts the binary in ./bin; add it to PATH
Windowsarduino-cli_latest_Windows_64bit.msi or .zipThe MSI sets PATH for you; with the zip, add the folder to PATH
Allarduino-cli versionChecks the install and prints the version

After installing, your first job is to create a config file with arduino-cli config init. It is written to the data folder that holds the board packages: %LOCALAPPDATA%\Arduino15 on Windows, ~/Library/Arduino15 on macOS and ~/.arduino15 on Linux, under the name arduino-cli.yaml. You can see its contents with arduino-cli config dump. The commands in this article follow Arduino CLI 1.x; most of them are the same in the older 0.x releases, only the format of the JSON output differs slightly.

First steps: installing cores and libraries

  1. Download the board list with arduino-cli core update-index. This is what the Boards Manager does when you open the IDE for the first time.
  2. Connect your board over USB and type arduino-cli board list. It shows the port (such as COM3 or /dev/ttyACM0) and, if recognised, the board's FQBN.
  3. Install the board's core: for Uno, Nano and Mega it is arduino-cli core install arduino:avr. core list shows what is installed.
  4. Search for and install the library you need: arduino-cli lib search DHT, then arduino-cli lib install "DHT sensor library". Dependencies such as Adafruit Unified Sensor come along automatically.
  5. If you need a specific version, add it after an @: lib install "DHT sensor [email protected]". The same works for cores: core install esp32:[email protected].
  6. Create a new sketch: arduino-cli sketch new Merhaba. You get a Merhaba folder containing Merhaba.ino; the folder name and the .ino name must match.

On clone boards board list often shows only the port, not the board name. That is because USB-to-serial chips such as the CH340 don't know which board they sit on; it's fine, you simply type the FQBN yourself. If no port appears at all, check the driver first; the steps are in the CH340 driver installation guide. The table below collects the FQBNs of the most common boards.

BoardFQBNNote
Arduino Unoarduino:avr:unoUno R3 and clones
Arduino Nanoarduino:avr:nanoNew bootloader
Arduino Nano (old bootloader)arduino:avr:nano:cpu=atmega328oldMost CH340 clones
Arduino Mega 2560arduino:avr:megaATmega2560
ESP32 dev boardesp32:esp32:esp32ESP32 DevKit, 30/38 pins
ESP32-S3esp32:esp32:esp32s3CDCOnBoot=cdc for native USB
ESP32-C3esp32:esp32:esp32c3Includes Super Mini boards
NodeMCU (ESP8266)esp8266:esp8266:nodemcuv2Needs the ESP8266 package
Raspberry Pi Pico / Pico Wrp2040:rp2040:rpipico / rpipicowNeeds the arduino-pico package

Compiling and uploading: compile and upload

The basic pair is this: arduino-cli compile -b arduino:avr:uno Merhaba compiles the sketch and arduino-cli upload -b arduino:avr:uno -p COM3 Merhaba uploads the last build to the board. To combine them, add -u -p COM3 to the compile command; if the build succeeds, the upload starts right away. On Linux the port looks like /dev/ttyACM0 (the Uno's original USB chip) or /dev/ttyUSB0 (CH340 clones), on macOS /dev/cu.usbmodem… or /dev/cu.usbserial…. The test sketch below compiles unchanged on Uno, ESP32 and Pico; it prints the board type and build time to the serial port, so you can tell that the code on the board is really the new one.

C++ (Arduino IDE)
1// Arduino CLI deneme sketch'i / Arduino CLI test sketch
2// Uno, ESP32 ve Pico için derlenir / Compiles for Uno, ESP32 and Pico
3
4#ifndef LED_BUILTIN
5#define LED_BUILTIN 2  // Bazı ESP32 kartlarında tanımsız / Undefined on some ESP32 boards
6#endif
7
8const unsigned long ARALIK_MS = 500;  // Yanıp sönme aralığı / Blink interval
9unsigned long sonZaman = 0;           // Son değişim zamanı / Last toggle time
10bool ledDurum = false;                // LED durumu / LED state
11
12void setup() {
13  pinMode(LED_BUILTIN, OUTPUT);
14  Serial.begin(115200);
15  delay(1000);  // Seri portun açılmasını bekle / Wait for the serial port
16#if defined(ARDUINO_ARCH_ESP32)
17  Serial.println("Kart / Board: ESP32");
18#elif defined(ARDUINO_ARCH_RP2040)
19  Serial.println("Kart / Board: Raspberry Pi Pico");
20#elif defined(ARDUINO_ARCH_AVR)
21  Serial.println("Kart / Board: AVR (Uno, Nano, Mega)");
22#endif
23  // Derleme zamanı: yeni kodun yüklendiğini gösterir / Build time: proves the new code is on the board
24  Serial.print("Derleme / Built: ");
25  Serial.println(__DATE__ " " __TIME__);
26#ifdef BG_DEBUG
27  Serial.println("Hata ayıklama açık / Debug on");
28#endif
29}
30
31void loop() {
32  unsigned long simdi = millis();  // Geçen süre / Elapsed time
33  if (simdi - sonZaman >= ARALIK_MS) {
34    sonZaman = simdi;
35    ledDurum = !ledDurum;
36    digitalWrite(LED_BUILTIN, ledDurum ? HIGH : LOW);
37#ifdef BG_DEBUG
38    Serial.println(ledDurum ? "LED: ON" : "LED: OFF");
39#endif
40  }
41}
FlagWhat it doesExample
-b, --fqbnSelects the board-b arduino:avr:mega
-p, --portUpload port-p /dev/ttyUSB0
-u, --uploadUploads after compilingcompile -u -p COM3
-e, --export-binariesCopies the output to the sketch's build folder.hex, .bin, .uf2
--output-dirWrites the output to a folder you choose--output-dir build-out
--build-propertyOverrides a build setting, adds definescompiler.cpp.extra_flags=-DBG_DEBUG
--warnings allTurns on all compiler warnings--warnings all
-v, --verboseShows every build and upload commandcompile -v
--cleanIgnores the cache and builds from scratchcompile --clean

The BG_DEBUG sections in the code only run if you define that name while compiling: --build-property "compiler.cpp.extra_flags=-DBG_DEBUG". That way you get a debug build and a quiet build from the same code. The official examples use build.extra_flags, but the ESP32 package stores its USB and board settings in that variable; if you overwrite it, the serial port can disappear on S3 and C3 boards. compiler.cpp.extra_flags, on the other hand, is left empty for the user and is safe on both the Uno and the ESP32.

If another program holds the port during upload (the IDE's Serial Monitor, an open arduino-cli monitor or software such as Cura), the upload stops with a "port busy" or "access denied" error. Close the monitor first. If you get "permission denied" on Linux the first time, add your user to the dialout group (sudo usermod -aG dialout $USER) and log out and back in.

Everyday Arduino CLI commands

CommandWhat it does
arduino-cli updateRefreshes both the board and library indexes
arduino-cli outdated / upgradeLists outdated packages / upgrades them all
arduino-cli core search esp32Searches board packages
arduino-cli board listall unoLists boards and FQBNs from installed cores
arduino-cli board details -b esp32:esp32:esp32Shows the board's menu options (partitions, speed)
arduino-cli lib listShows installed libraries and versions
arduino-cli lib upgradeUpgrades libraries to the latest version
arduino-cli lib install --zip-path kutuphane.zipInstalls a library from a ZIP (enable unsafe install first)
arduino-cli config set library.enable_unsafe_install trueAllows installs from ZIP and Git
arduino-cli monitor -p COM3 -c baudrate=115200Opens the serial monitor, quit with Ctrl+C
arduino-cli board attach -p COM3 -b arduino:avr:unoSaves board and port to sketch.yaml
arduino-cli cache cleanClears the download cache

Arduino CLI for ESP32 boards

Because the ESP32 is not in the official Arduino list, you first add its package URL: arduino-cli config add board_manager.additional_urls https://espressif.github.io/arduino-esp32/package_esp32_index.json. Then run core update-index and core install esp32:esp32. The package downloads roughly 500 MB of compilers and tools, so the first install takes a few minutes. If an older project depends on version 2.x, pick it with core install esp32:[email protected]; for the changes in 3.x see the ESP32 core 3 migration errors guide. Board menu options go into the FQBN: -b esp32:esp32:esp32:PartitionScheme=huge_app,UploadSpeed=921600 selects the large app partition and fast upload.

Don't guess which option names are valid: arduino-cli board details -b esp32:esp32:esp32s3 lists every menu and its values. To see Serial output over the native USB of the ESP32-S3 and C3 you usually need to add CDCOnBoot=cdc. If the upload hangs at "Failed to connect", hold the BOOT button; details are in the ESP32 Failed to connect guide.

Raspberry Pi Pico boards

The most popular Arduino core for the Pico is Earle Philhower's arduino-pico package. Add its URL just like the ESP32's: arduino-cli config add board_manager.additional_urls https://github.com/earlephilhower/arduino-pico/releases/download/global/package_rp2040_index.json, then core install rp2040:rp2040. The FQBN is rp2040:rp2040:rpipico for the Pico, rp2040:rp2040:rpipicow for the Pico W and rp2040:rp2040:rpipico2 for the Pico 2. If the board has never run Arduino code (a new board or one with MicroPython), hold BOOTSEL while plugging in USB for the first upload; the board shows up as a drive called RPI-RP2. In that case, dragging the .uf2 file produced by compile -e onto the drive always works. On later uploads the board appears as a serial port and upload puts it into bootloader mode by itself. MicroPython code, by contrast, is uploaded with Thonny or mpremote, not with Arduino CLI.

Bulk upload with a script: one sketch, many boards

Imagine a classroom workshop where fifteen Unos need the same code. In the IDE, selecting the port and clicking Upload for every board is slow and error-prone. With the CLI you compile once, write the output to a folder and send that ready-made file to each port in turn with upload --input-dir, so you never wait for a rebuild. The Python script below does exactly that; you can pass the ports by hand or let the script find boards with a matching FQBN in the output of board list --format json.

Python
1# Arduino CLI ile toplu yükleme / Bulk upload with Arduino CLI
2# Kullanım / Usage: python3 toplu_yukle.py Merhaba arduino:avr:uno [COM3 COM4 ...]
3import json
4import subprocess
5import sys
6
7SKETCH = sys.argv[1] if len(sys.argv) > 1 else "Merhaba"
8FQBN = sys.argv[2] if len(sys.argv) > 2 else "arduino:avr:uno"
9PORTS = sys.argv[3:]  # Elle verilen portlar / Ports given by hand
10OUT = "build-out"     # Derleme çıktısı klasörü / Build output folder
11
12
13def run(args):
14    # arduino-cli komutunu çalıştır / Run an arduino-cli command
15    r = subprocess.run(["arduino-cli"] + args, capture_output=True, text=True)
16    if r.returncode != 0:
17        print(r.stderr.strip())
18    return r
19
20
21# 1) Bir kez derle / Compile once
22if run(["compile", "-b", FQBN, "--output-dir", OUT, SKETCH]).returncode != 0:
23    sys.exit("Derleme başarısız / Compile failed")
24
25# 2) Port verilmediyse kartları bul / Find boards if no port was given
26if not PORTS:
27    data = json.loads(run(["board", "list", "--format", "json"]).stdout or "[]")
28    found = data.get("detected_ports", []) if isinstance(data, dict) else data
29    for p in found:
30        addr = p.get("port", {}).get("address")
31        fqbns = [b.get("fqbn") for b in p.get("matching_boards", [])]
32        if addr and FQBN in fqbns:
33            PORTS.append(addr)
34
35print(f"{len(PORTS)} kart / boards: {PORTS}")
36
37# 3) Aynı dosyayı her porta yükle / Upload the same binary to every port
38ok = 0
39for addr in PORTS:
40    r = run(["upload", "-b", FQBN, "-p", addr, "--input-dir", OUT])
41    ok += r.returncode == 0
42    print(addr, "TAMAM / OK" if r.returncode == 0 else "HATA / FAIL")
43
44print(f"Sonuç / Result: {ok}/{len(PORTS)}")

Run the script next to the sketch folder with python3 toplu_yukle.py Merhaba arduino:avr:uno. Genuine Unos are recognised by their FQBN and found automatically; CH340 clones are not recognised, so add their ports at the end of the command: … arduino:avr:uno COM3 COM4 COM5. The script prints OK or FAIL for every port and finally tells you how many boards succeeded. If you use a USB hub, pick one with its own power supply; ten boards easily exceed 500 mA together. ESP32 boards are flashed the same way; you only change the FQBN.

VS Code tasks: compile and upload with one key

Writing code in VS Code and leaving the build to Arduino CLI is very comfortable. Create a .vscode/tasks.json file in the project folder with two tasks: one runs arduino-cli compile, the other arduino-cli compile -u. Make the compile task the default and you build with Ctrl+Shift+B (Cmd+Shift+B on macOS); pick the upload task from Run Task in the Terminal menu. Use $gcc as the problemMatcher so you can click error lines to jump into the file. The C/C++ extension is enough for code completion; compile --only-compilation-database generates a compile_commands.json the extension can read. If you want a fuller environment, PlatformIO is also a good choice.

tasks.json fieldCompile taskUpload task
labelArduino: DerleArduino: Yükle
typeshellshell
commandarduino-cli compile -b arduino:avr:uno ${workspaceFolder}arduino-cli compile -u -p COM3 -b arduino:avr:uno ${workspaceFolder}
group{ kind: build, isDefault: true }build
problemMatcher$gcc$gcc

Sharing settings with the Arduino IDE

Good news: with the default settings the CLI and the IDE use the same folders. Board packages go into the data folder (Arduino15) and libraries into the libraries subfolder of your sketchbook, so the CLI sees a library you installed in the IDE right away, and vice versa. The only difference is the additional board URLs: IDE 2 keeps its settings in ~/.arduinoIDE/arduino-cli.yaml (on Windows, .arduinoIDE in your user folder). Instead of adding the same URLs to the CLI one by one, you can point at that file with --config-file ~/.arduinoIDE/arduino-cli.yaml. To avoid typing board and port in every project, run board attach in the sketch folder; default_fqbn and default_port are written to sketch.yaml and later compile and upload commands no longer need -b and -p. Add a profiles section to the same file to pin core and library versions too, and compile -m profile_name gives you the same result even years later.

FolderWindowsmacOSLinux
Data (board packages)%LOCALAPPDATA%\Arduino15~/Library/Arduino15~/.arduino15
Sketchbook and librariesDocuments\Arduino~/Documents/Arduino~/Arduino
IDE 2 settings file%USERPROFILE%\.arduinoIDE\arduino-cli.yaml~/.arduinoIDE/arduino-cli.yaml~/.arduinoIDE/arduino-cli.yaml

Common errors and fixes

Error messageCauseFix
Platform 'esp32:esp32' not foundPackage URL missing or index outdatedconfig add board_manager.additional_urls, then core update-index
Missing FQBN (Fully Qualified Board Name)No -b given and no sketch.yamlAdd -b or run board attach
fatal error: DHT.h: No such file or directoryLibrary not installedFind the name with lib search, install with lib install
main file missing from sketchFolder name differs from the .ino nameMake them match: Merhaba/Merhaba.ino
avrdude: stk500_getsync(): not in syncWrong port, wrong Nano bootloader or cableCheck the port with board list, try cpu=atmega328old on a Nano
--git-url and --zip-path are disabled by defaultSafety setting is offconfig set library.enable_unsafe_install true
To understand an error, run the same command again with -v: the CLI shows the exact command lines it sends to the compiler and to avrdude. A general list of upload problems is in Arduino code won't upload, and the meaning of compiler messages in Arduino compile errors.

The best way to learn Arduino CLI is to compile and upload a project you already know from the command line. The LED, button and sensor projects in the BlueGrays app come with a step-by-step wiring diagram and ready-made code, so you can copy the code and try sending it to your board with the compile and upload commands you learned here right away.

Frequently asked questions

What is Arduino CLI?

Arduino CLI is Arduino's official command-line tool. It installs board packages and libraries, compiles sketches, uploads them to the board and opens a serial monitor. Arduino IDE 2 uses the same engine in the background, so the build results are identical to the IDE's.

How do I upload code with Arduino CLI?

First find the port with arduino-cli board list, then type arduino-cli compile -b arduino:avr:uno -u -p COM3 Merhaba. This compiles the sketch and, if it succeeds, uploads it to the board right away. Use board attach so you don't have to type the board and port every time.

How do I find the FQBN in Arduino CLI?

With the board connected, arduino-cli board list often shows the FQBN directly. If it doesn't, a search like arduino-cli board listall uno lists the board names and FQBNs from your installed cores. For menu options, use board details -b.

How do I add ESP32 to Arduino CLI?

Add Espressif's package URL with config add board_manager.additional_urls, then run core update-index and core install esp32:esp32. The FQBN for classic ESP32 boards is esp32:esp32:esp32. For a specific version you can write something like core install esp32:[email protected].

Does Arduino CLI see libraries installed in the IDE?

Yes, with the default settings both use the same sketchbook and Arduino15 folders. Libraries and board packages you installed in the IDE are ready in the CLI too. Only the additional board URLs live in the IDE's own settings file; add them to the CLI or point at that file with --config-file.

How do I get a hex or bin file with Arduino CLI?

Add -e (--export-binaries) to the compile command and the .hex, .bin and, for the Pico, .uf2 files are copied to the build subfolder of the sketch. Use --output-dir for a folder of your choice. You can upload these files on another computer with upload --input-dir or directly with avrdude and esptool.

See all projects
LED Blink
AR-1Beginner

LED Blink

The very first hello of electronics: switching a single LED on and off. The Arduino keeps the LED on for one second and off for one second, so you can easily follow every blink.

4.6(203)
1380
LED Control with a Push Button (Push)
AR-9Beginner

LED Control with a Push Button (Push)

Just like a doorbell: the light stays on as long as you press, and goes off when you let go.

4.8(118)
283
HC-SR04 Distance Measurement (Serial Display)
AR-27Beginner

HC-SR04 Distance Measurement (Serial Display)

The HC-SR04 sensor works just like a bat finding its way in the dark: it sends out a sound you cannot hear, listens for the echo and measures how far away the object in front of it is.

4.6(52)
94
Temperature and Humidity with DHT11
AR-55Intermediate

Temperature and Humidity with DHT11

How warm is your room, and is the air humid or dry? The DHT11 sensor measures temperature and humidity, and the Arduino writes the values on a two-line LCD screen, refreshing every couple of seconds.

4.7(47)
96
LED Blink with ESP32
ES-1Beginner

LED Blink with ESP32

Teaches basic GPIO output usage with ESP32. We achieve a blinking effect by turning an LED on and off from a digital pin. ESP32 version of the classic blink project on Arduino UNO; the basic blink commands in the Arduino environment are the same, but the ESP32's pin layout and 3.3 V GPIO levels differ from those of the Arduino UNO.

4.7(38)
114
ESP32 Built-in LED Blink
ES-4Beginner

ESP32 Built-in LED Blink

Blinking the built-in blue LED on the ESP32 DevKit V1. No external components required! The first project you should try when you buy an ESP32. GPIO 2 is connected to the built-in LED.

4.8(29)
55
Raspberry Pi Pico Onboard LED Blink (Pico and Pico W)
PI-1Beginner

Raspberry Pi Pico Onboard LED Blink (Pico and Pico W)

The opening project of the Raspberry Pi Pico series! We blink the Pico's green built-in LED to confirm the board works, the classic "Hello World" first experiment. No external parts needed, just the Pico and a USB cable. The code is written in MicroPython, the language officially supported by the Raspberry Pi Foundation.

5.0(1)
11
Raspberry Pi Pico: Controlling an External LED (Breadboard)
PI-2Beginner

Raspberry Pi Pico: Controlling an External LED (Breadboard)

The next step after the Pico's built-in LED: connect an external LED on a breadboard and control it through pin GP14. You'll learn how to use any of the Pico's GPIO pins as an output, the LED's polarity (long leg = anode/+, short leg = cathode/–) and why a current-limiting resistor (220Ω) is a must. Without the resistor, too much current flows through the LED and it can burn out.

4.5(2)
7