How to Use VS Code for Creating and Uploading Arduino Sketches

Learn how to use the popular VS Code IDE to develop Arduino projects and upload your sketches to Arduino boards directly, without using Arduino IDE.

How-To-Use-VS-Code-To-Create-and-Upload-Arduino-Sketches-Featured-Image-01-1-1
VS Code + Arduino = 🎉

Visual Studio Code (VS Code) is a very popular general-purpose Integrated Development Environment (IDE). An IDE is a software that integrates a text editor, programming interface, debug view, and project management in one place. The open-source project is led by Microsoft and runs on all operating systems. What makes VS Code the favorite choice of all developers is how fast it runs, the customizations, and the availability of awesome extensions that extend the capabilities of the software. One such extension is the Arduino Extension developed by Microsoft itself.

In this tutorial, we will learn how to use VS Code and its extensions to develop Arduino projects and upload them to your Arduino boards directly, without using the Arduino IDE.

We can develop embedded firmware for you

CIRCUITSTATE can develop embedded firmware for any microcontroller/microprocessor including 8051, PIC, AVR, ARM, STM32, ESP32, and RISC-V using industry-leading SDKs, frameworks, and tools. Contact us today to share your requirements.

Electronics Networking Vector Image

Why Use VS Code for Arduino?

The Arduino IDE v1.8 has very limited capabilities in terms of features required for a modern IDE. But it is done so by choice. Arduino’s goal is to make technology less daunting for non-tech-related folks. So simplicity and ease of use are the priorities. Arduino is developing a newer and much more capable IDE version 2, and it is in beta mode as of writing this article. So while that is in the works, we can use the most modern VS Code IDE with its rich features to develop Arduino projects. If you have not used any IDEs other than Arduino IDE, this is a good place to learn how to start and what you can accomplish with VS Code. Some of the great features of VS Code are,

  • Free and Open-source: You don’t need to pay for downloading and getting updates.

  • Cross-platform: VS Code runs on almost all platforms and you get seamless updates.

  • Extremely Fast and Lightweight: Even though written mostly in Javascript and Typescript, VS Code runs fast on your computer while consuming fewer resources.

  • Near-infinite Customization: VS Code uses text-based JSON files for configuration and almost any feature of VS Code can be customized by updating the JSON settings files.

  • Awesome Extensions: VS Code has a marketplace for extensions/plugins developed by both Microsoft and other developers. Extensions extend the capabilities of VS Code. The underlying web technologies used for VS Code make it easy to develop powerful extensions.

  • Beautiful Themes and Icons: VS Code is highly customizable in its appearance; from fonts to icons. Themes and icon packs can be downloaded from the extension marketplace.

  • Integrated Consoles/Terminals: You don’t need to leave the VS Code window to run your console applications such as Powershell. Terminals are an integrated feature of VS Code and you can run multiple terminals at the same time.

  • Integrated Git Version Control: Versioning your projects is easy with VS Code.

  • Integrated Github Syncing: You can sign in with your GitHub account and push/pull your projects from GitHub.

  • Rich Text Editor: The text editor comes with powerful editing features that help you type, copy, paste, duplicate, find, and replace items much faster than conventional text editors. VS Code can selectively use syntax highlighting depending on the type of file opened.

  • Code Completion: VS Code can suggest function names, variables, class names, keywords, etc. as you start typing. If you choose a suggestion that is a snippet, VS Code will automatically create the basic construct/template for that keyword. For example, a switch keyword will create a new switch construct with brackets and right indentations.

  • Code IntelliSense: VS Code can scan your project dependencies, locate where they are, and find code references from all those files. You can hover over an item to see its value or reference and Ctrl + Left Click to open the reference.

Installing VS Code

To get started, first download VS Code for your preferred OS. There are two types of installers for VS Code.

  1. System Installer – this is used for operating systems with the main user as the sole administrator of the system. This installer and subsequently the VS Code installation runs with administrator privileges. If you are the admin of your system, you can choose this installer.

  2. User Installer – this can be used by a user of an operating system without admin privileges. VS Code will not need admin privileges to run. If you are not an admin of your system (for example, if the computer is provided by your employer), you can choose the user installer. When a user-installed VS Code is run with admin privileges, automatic updates will be paused.

Run the downloaded installer and choose a path on your system. By default, VS Code is installed under C:\Users\{Username}\AppData\Local\Programs\Microsoft VS Code. More information on installing can be found here. Once installed launch VS Code from your desktop or main menu. You will be welcomed with the getting started page. The screen you will see can be different from ours because we have customized the looks and functionalities of our VS Code.

VS-Code-Arduino-Get-Started-CIRCUITSTATE-01
Your screen may look different

The basic layout is as follows,

VS-Code-Arduino-Basic-Layout-CIRCUITSTATE-01
Basic layout

VS Code comes with a simple and intuitive layout that maximizes the space provided for the editor while leaving ample room to browse and access the full context of your folder or project. The UI is divided into five areas:

  • Editor – The main area to edit your files. You can open as many editors as you like side by side vertically and horizontally.
  • Side Bar – Contains different views like the Explorer to assist you while working on your project.
  • Status Bar – Information about the opened project and the files you edit.
  • Activity Bar – Located on the far left-hand side, this lets you switch between views and gives you additional context-specific indicators, like the number of outgoing changes when Git is enabled.
  • Panels – You can display different panels below the editor region for output or debug information, errors and warnings, or an integrated terminal. Panel can also be moved to the right for more vertical space.
  • Action Buttons – Allows you to perform various tasks provided by the extensions.

Each time you start VS Code, it opens up in the same state it was in when you last closed it. The folder, layout, and opened files are preserved. Open files in each editor are displayed with tabbed headers (Tabs) at the top of the editor region.

Workspace

In VS Code, a workspace refers to a folder where your project files are stored. When you open a folder, all the files and folders inside that root folder will be displayed on the file explorer on the sidebar. You can create new files, and delete or rename files right from the sidebar. VS Code will automatically create a folder called .vscode to store configuration files and temporary files.

In Windows, you can right-click on an empty space in a folder in File Explorer to open the context menu and use Open with Code option to open a folder as a workspace. You can also open a folder from File menu. By default, the folder will open in the existing window if the VS Code is already open. To open the new workspace in a different window, simply hold down Shift button when you click the context menu option.

Open-VS-Code-from-Context-Menu-CIRCUITSTATE-01
Open with Code

Installing Arduino Extension

The Arduino extension is developed by Microsoft. You can install it from the extension marketplace. Launch VS Code and from the Extensions menu (Ctrl + Shift + X) search for “Arduino”. Install the Arduino extension. After installing, reload the IDE. The Arduino Extension is used to work with either Arduino IDE or Arduino-CLI (command-line version) installations on a system. But Microsoft has recently dropped support for the Arduino IDE and that means you need to install Arduino-CLI to get the extension to work. If you do not want to install Arduino-CLI manually, the extension now comes with Arduino-CLI as part of it. So if you don’t set a custom path for the Arduino-CLI, the extension will use the default one. In this tutorial, we will use a custom installation of Arduino-CLI and set the path on the Arduino extension settings.

Installing the Arduino-CLI is very easy and both the Arduino IDE and CLI versions can coexist in a system without any issues. First, download the suitable Arduino-CLI installer from the official page. We used the 64-bit Windows exe. This will simply download a ZIP containing the exe file which you need to relocate to some other drive such as the C drive. If you use the MSI installer instead, you can choose the installation directory.

Once installed, you can go to the installation directory and run the application from the command line with the following. The “.\” prefix is needed to run an executable file from the root folder in Powershell.

.\arduino-cli help core
PowerShell

In our case, we have the Windows Terminal application installed and therefore we can launch the terminal from any folder using the File Explorer context menu. In order to run the arduino-cli from anywhere on your system, simply add the installation directory to the Path environment variable.

Arduino CLI help command in Windows terminal powershell
Running the help core command

The Arduino-CLI consists of a single executable. So you might wonder where its configuration files, platforms, and libraries are. By default, Arduino-CLI uses three directories for its functionalities.

  1. data – for storing all configurations and platform files.
  2. downloads – for downloading installation packages, libraries, etc.
  3. user – where libraries and sketches will be stored.

You can determine the locations of three directories by running the configuration dump command.

PS C:\Users\Vishnu Mohanan> arduino-cli config dump
board_manager:
  additional_urls: []
daemon:
  port: "50051"
directories:
  data: C:\Users\Vishnu Mohanan\AppData\Local\Arduino15
  downloads: C:\Users\Vishnu Mohanan\AppData\Local\Arduino15\staging
  user: D:\Code\Arduino
library:
  enable_unsafe_install: true
logging:
  file: ""
  format: text
  level: info
metrics:
  addr: :9090
  enabled: true
output:
  no_color: false
sketch:
  always_export_binaries: false
updater:
  enable_notification: true
PowerShell

The data folder is the same as the Arduino IDE folder where all your platform and configurations are stored. So you can keep it as is. The downloads directory can also be kept the same. However, the user directory may require change if you want to use your already installed libraries and created sketches. In order to do that, you need to create a configuration file specific to the Arduino-CLI. This can be done by the following command.

arduino-cli config init
PowerShell

This will simply create a new YAML file inside the data directory. This file will have the same contents you get when you execute the config dump command. You can open the file in a text editor and change the user directory to your already existing sketchbook folder and save it. In our case, this is at D:\Code\Arduino. To test if the configuration is working, simply try to list the installed libraries using the following command.

arduino-cli lib list
PowerShell
Arduino CLI library list command in Windows terminal powershell
List the installed libraries

The next step is to tell the VS Code Arduino Extension where the Arduino-CLI is located. This can be done by going to the settings of the Arduino Extension and adding the installation path as the value to Arduino: Path option. Reload VS Code after that and you are ready to use VS Code for compiling and uploading your Arduino projects.

Install-VS-Code-Arduino-Extension-CIRCUITSTATE-01
Install Arduino extension
VS-Code Arduino Extension Settings Arduino-CLI Path Configuration CIRCUITSTATE Electronics
Set the Arduino-CLI path

The main features of the Arduino extension of VS Code are,

  • IntelliSense and syntax highlighting for Arduino sketches.
  • Verify and upload your sketches in Visual Studio Code.
  • Built-in board and library manager.
  • Built-in example list.
  • Built-in serial monitor.
  • Snippets for sketches.
  • Automatic Arduino project scaffolding.
  • Command Palette (F1) integration of frequently used commands (e.g. Verify, Upload…).
  • Integrated Arduino Debugging for supported boards.

Installting the Arduino extension along with other extensions such as PlatformIO can create conflicts as these extensions will try to take control of the workspace and files simultaneously. Therefore it is a good idea to disable PlatformIO or other conflicting extensions on your Arduino workspace. You can do this by clicking on the small cog icon on the extension and choose Disable (Workspace) option. You should also disable the Arduino extension when working with PlatformIO projects.

Opening Arduino Sketch

To start using the Arduino extension, you first need to open a folder that contains a .ino file. The Arduino extension will be activated on a workspace with at least one .ino file. We will create a folder called Blink in our Sketches folder and open it with VS Code.

VS-Code-Arduino-Blink-Folder-CIRCUITSTATE-01
Blink sketch

When you first open the sketch, the Arduino extension would not have configured the workspace for Arduino projects. To configure the workspace, start by selecting the board you are trying to use. Find the <Select Board> button on the right side of the status bar and click on it. A new tab will open on the right side, where you can search for the board. Here, we are using the Arduino Nano 33 IoT for running our examples.

VS-Code-Arduino-Select-Board-CIRCUITSTATE-01
Select your board

You can see the red squiggly underlines on the code. The squiggles are added by the Arduino IntelliSense and they indicate errors. You can see what the error is by hovering over the text. Since we don’t have any syntactical or logical errors in the code we just created, these squiggles will disappear once the IntelliSense is configured correctly.

Next, we need to choose the serial port to which the board is connected. You can click on the <Select Serial Port> button on the status bar to select a port from a list of available ports.

VS-Code-Arduino-Select-Serial-Port-CIRCUITSTATE-01
Select serial port

Since we are not using any external programmers, we don’t need to set up a programmer. You must also notice that the status bar has an item called Win32. This indicates that the current workspace is expecting a Windows 32-bit C/C++ project from the contents of the file we opened. But we actually need a different configuration for compiling Arduino sketches. Luckily, the Arduino extension can create this for us. Simply open the Command Palette with the shortcut Ctrl + Shift + P and start typing “rebuild intellisense configuration”. As soon as you start typing it VS Code will fetch a list of similar commands, from which you can select the Arduino: Rebuild IntelliSense Configuration or press Ctrl + Alt + I. If that doesn’t work for some reason, use Arduino:Verify (Ctrl + Alt + R) option to start compiling the sketch. This will generate a new Arduino configuration in the c_cpp_properties.json file. Then reload VS Code.

Building the intellisense configuration can fail if the code compilation process fails when you have errors in your code. That means, your code should be error free in order to generate intellisense configuration for the first time.

This will open a new OUTPUT panel and start printing lots of text messages. What is happening the Arduino extension is trying to find the dependencies from the Arduino packages and use them to build the IntelliSense data. The dependencies can include header files, libraries, source files, or other configuration data. Once the analysis is complete, the Arduino extension will create a new configuration called arduino.json and save it to the .vscode folder. The previous Win32 item on the status bar will now change to Arduino. In case it did not change, you can restart the VS Code for the changes to take effect. The error squiggles will also disappear now.

VS-Code-Arduino-Code-Analysis-Complete-CIRCUITSTATE-01
IntelliSense building complete

Let’s explain a few things you can see at different locations on the window.

  1. On the sidebar file explorer menu, you can see the configuration files (JSON files) created by VS Code that are inside the .vscode folder. They are automatically generated and updated by VS Code when you update the settings from any other place. Any changes you make to these files will be overwritten by VS Code the next time you compile the sketch.

  2. At the bottom of the sidebar, there is a list of items that can be expanded. These are C/C++ code explorer windows. Among them is the ARDUINO EXAMPLES. This list is provided by the Arduino extension and you can open all Arduino examples from there.
VS-Code-Arduino-Example-Sketches-List-CIRCUITSTATE-01
Arduino example sketches
  1. Ln 11, Col 26 indicates the line and column of the cursor location.
  2. Spaces: 2 indicates the number of spaces used for auto-indentation.
  3. LF indicates the end of line sequence is a Linefeed character.
  4. C++ indicates the language mode.
  5. Blink.io indicates the current file active for compilation. And yes, you can open multiple Arduino sketches in different folders and you can choose which one to compile. This makes it easy to manage multiple Arduino sketches at once, for example when you are working with an Arduino library.
  6. Clicking Reload will reload VS Code. You need to install the Reload extension for this.
  7. On the action buttons section, there are two buttons that say Arduino:Upload (Ctrl + U) and Arduino:Verify (Ctrl + Alt + R). These buttons are placed by the Arduino extension and you can use them to compile and upload your sketches to the selected board.

Compiling and Uploading

With that much explanation, we can now proceed to compile and upload the blink sketch. Click the Arduino:Upload to button to compile and upload the sketch to your board. The OUTPUT window will open automatically and print all the messages generated during the process.

Now let’s write a small Serial Call-Response sketch to test the serial monitor feature of VS Code. We should initialize the serial port with begin() function. And look how VS Code is suggesting the functions as soon as we type Serial... This is possible because IntelliSense knows where these functions are located and automatically fetches them as we start typing.

VS-Code-Arduino-Function-Suggestion-CIRCUITSTATE-01
Suggestions from IntelliSense

Upload the following code and open the serial monitor by pressing the plug icon in the status bar.

void setup() {
  Serial.begin (115200);
  while (!Serial);
}

void loop() {
  if (Serial.available()) {
    String inputString = Serial.readString();
    Serial.println (inputString);
  }
}
C++
How-to-Use-VS-Code-to-Write-and-Upload-Arduino-Sketches-Open-Serial-Monitor-CIRCUITSTATE-02
Send any message and it will be echoed back

VS Code now has a functional Serial Monitor extension from Microsoft which you can download from the extension marketplace. Simply click the SERIAL MONITOR tab to open it. Then specify the connection type, port, and baudrate to begin communication. You can send any message by typing it in the input box at the bottom and pressing Send Message. Any message you send will be echoed back by the Arduino board. You can also try the same with the Arduino Serial monitor.

Arduino-Serial-Monitor-CIRCUITSTATE-01
The simple and functional Arduino Serial Monitor ✨

Extension Commands

The Arduino extension doesn’t expose all functionalities via buttons or menu items. Instead, all functionalities can be invoked from the VS Code command palette. You can open the command palette from Manage → Command Palette or use the shortcut Ctrl + Shift + P. You can also assign a different shortcut if you want. Additionally, you can click on the search bar at the top of the VS Code window and start typing > before running a command.

As soon as you type “Arduino” on the command palette, you will get a list of supported commands. The following commands are available for the Arduino extension. You can also assign shortcuts to these commands. For example, we use the shortcut Ctrl + Alt + U to upload code through the selected external programmer using the command Arduino: Upload Using Programmer.

  • Arduino: Board Manager: Manage packages for boards. You can add 3rd party Arduino board by configuring Additional Board Manager URLs in the board manager.

  • Arduino: Change Board Type: Change board type or platform.

  • Arduino: Change Timestamp Format: Change the format of the timestamp printed before each line of Serial Monitor output.

  • Arduino: Close Serial Monitor: Stop the serial monitor and release the serial port.

  • Arduino: Examples: Show a list of examples.

  • Arduino: Initialize: Scaffold a VS Code project with an Arduino sketch.

  • Arduino: Library Manager: Explore and manage libraries.

  • Arduino: Open Serial Monitor: Open the serial monitor in the integrated output window.

  • Arduino: Select Serial Port: Change the current serial port.

  • Arduino: Upload: Build sketch and upload to Arduino board.

  • Arduino: CLI Upload: Upload compiled code without building sketch (CLI only).

  • Arduino: Upload Using Programmer: Upload using an external programmer.

  • Arduino: CLI Upload Using Programmer: Upload using an external programmer without building a sketch (CLI only).

  • Arduino: Verify: Build sketch.

  • Arduino: Rebuild IntelliSense Configuration: Forced/manual rebuild of the IntelliSense configuration. The extension analyzes Arduino’s build output and sets the IntelliSense include paths, defines, and compiler arguments accordingly.
VS-Code Arduino Extension Command List from Command Palatte CIRCUITSTATE Electronics
List of Arduino extension commands in VS Code

Tips & Tricks

Below is a list of tips and tricks we know of. You can help us expand this list if you know more tricks to save time and increase productivity.

  • Hover over any item to see its declaration and press Ctrl key while hovering to see the part of the definition of the item.
VS-Code-Arduino-Intellisense-Reference-CIRCUITSTATE-01
  • Ctrl + Left Click on an item opens its reference. If there are multiple references, you will get an interactive list of them.
  • User Arduino IDE’s Use external editor feature to always use VS Code as the editor. This will sync changes made in VC Code to the Arduino IDE.

  • Use Alt + Up / Down arrow keys combinations to move the active lines up or down.

  • User Alt + Left Click to place a cursor anywhere on the file and start typing at multiple locations at once.

  • Use Ctrl + Left / Right arrow keys to move the cursor through words than letters. Use the Shift key in combination with this to select the line instead of just moving the cursor.

  • Use Ctrl + Backspace to delete blocks of characters.

  • Use Shift + Home to the active line to the leftmost non-whitespace character. This helps to easily rewrite the current line.

  • Use Ctrl + L to select the entire active line.

  • Use Ctrl + Shift + K to delete a line.

  • Use Shift + Alt + Up / Down keys to duplicate the current line.

  • To copy an entire line, you don’t need to select it. Instead, simply press Ctrl + C when the cursor is anywhere on the line.

  • Similarly to cut a line simply press Ctrl + X. This can also be used to quickly delete a line.

  • Press the scroll wheel of your mouse and drag on your code to marquee select the code. This can also place multiple cursors at once.

  • Use Tab to indent to the right and Shift + Tab to indent to the left.

  • Use Ctrl + Shift + \ to jump to the matching bracket.

A complete list of default shortcuts can be found here in this PDF.

  1. Serial Monitor
  2. Git History
  3. GitLens
  4. Insert Date String
  5. hexdump for VS Code
  6. Reload extension
  1. Download VS Code
  2. VS Code Arduino Extension – Marketplace
  3. Arduino Extension – Github
  4. VS Code Shortcuts – PDF
Share to your friends
Vishnu Mohanan

Vishnu Mohanan

Founder and CEO at CIRCUITSTATE Electronics

Articles: 94

7 Comments

  1. These steps worked perfectly to setup VS with the Arduino Due board. But with Arduino Giga it didn’t work. The arduino.json and c_cpp_properties.json seem to be created correctly, but still I got squiggles in my code.

    • Thanks Stefan, for the feedback. We do not have an Arduino Giga board with us right now. So we can’t immediately test it. Are you able to compile sketches?

  2. I’ve downloaded the Arduino extension and I’m using the bundled Arduino CLI on VS code but I keep getting an error on the Output tab saying:
    [Starting] Verifying sketch 'Blink.ino'
    [Warning] Output path is not specified. Unable to reuse previously compiled files. Build will be slower. See README.
    Error opening sketch: no valid sketch found in /Users/username/Desktop/Blink: missing /Users/username/Desktop/Blink/Blink.ino
    [Warning] Failed to generate IntelliSense configuration.
    [Error] Verifying sketch 'Blink.ino': Exit with code=1.

    I’ve tried rebuilding the IntelliSense configuration using the command pallete command but I keep getting the same error. I’m also not sure exactly what the output path is for. There are no syntactical or logical errors in the script. Any help would be greatly appreciated.

    • The “Output Path” is a folder where your build files (generated during compilation) will be stored. Files in this folder may get rewritten during each compilation. Having an output path reduces the time it takes for subsequent compilations because all of the unchanged source files that are already compiled do not need to be compiled again. That’s why it says “Build will be slower”. It is not necessary to have a build directory though, but having it can speed up compilation. You can define the Output Path in the arduino.json file generated by VS Code Arduino extension, by adding the following code (as a new line in the JSON file), where we set the output path to a folder called “build” in the workspace (root) directory.

      "output": "${workspaceFolder}/build"

      An example arduino.json file will look like below.

      {
      "configuration": "DebugLevel=none",
      "board": "DFRobot:esp32:esp32-e",
      "port": "COM27",
      "sketch": "ESP32-Test.ino",
      "output": "${workspaceFolder}/build"
      }

      Now for the error part. It seems that the Arduino CLI is not able to find the sketch you are trying to compile in the folder you have specified. Are you sure you have saved the sketch to the right folder and opened VS Code in the same folder? If yes, try compiling the sketch with the Arduino CLI alone. Then we can isolate the source of the error. To open VS Code in any folder, you can right-click on the file explorer window and choose Open with VS Code.

      Intellisense collects path and library data from the compilation window itself. So if the code fails to compile, Intellisense will fail to obtain the data it needs.

  3. Thanks for the great overview.

    I am using the Microsoft Serial Monitor extension in Visual Studio Code, no need to open an external one and to me it ‘s doing the job

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.