Visual Studio Code for programming a Raspberry Pi

Visual Cues

© Lead Image © lightwise, 123RF.com

© Lead Image © lightwise, 123RF.com

Author(s):

Professional and casual Python developers save time and keystrokes in a Visual Studio Code development environment for remote coding of a Raspberry Pi.

Writing software code is heavy work, and professional code writers leverage software tools to create an effective environment that allows developers to work on code without affecting the users or breaking anything in the live environment.

Development environments are typically set up on a local machine or server that reflects the target production environment and contains the code being developed or modified. An integrated development environment (IDE) is a software application programming tool, deployed in a development environment to assist developers in maximizing their productivity and efficiency.

The IDE needs to be compatible with the programming language of interest and typically contains source code editors, a debugger, a compiler, and designers that can all be accessed through a single interface. Combining all of the development tools into one software suite helps the coder work on multiple tasks through one interface.

The repetitive commands used to write, run, and change code can be optimized in an IDE. Microsoft Visual Studio Code (VS Code) [1] is a tool for professional code developers (but see the "IDEs for All" box) that is usually used on standard Windows, Linux, and macOS machines; however, it can also be deployed to help make the life of a Raspberry Pi programmer easier.

IDEs for All

If you don't consider yourself a professional coder, why invest in an IDE? Maybe you're a code resurrectionist, or Frankenstein programmer.

Resurrectionists were paid body snatchers who exhumed the bodies of the recently dead for anatomists in the United Kingdom during the 18th and 19th centuries. In Mary Shelley's classic horror novel Frankenstein; or, The Modern Prometheus, Dr. Frankenstein stitches together an assortment of stolen body parts and attempts to imbue life into his creation.

Likewise, code resurrectionists look through Python code to find pieces that they can bring back to life by combining them with other pieces of code to make something useful. The cycle is similar to the instructions "wash, rinse, and repeat" found on a shampoo bottle: Find code snippets, combine them, modify them, write code when desperate, deploy the mix, and test. An IDE is the perfect tool for this programming cycle.

Environmental Decisions

VS Code is a streamlined code editor with support for development operations like debugging, task running, and version control. Although the Raspberry Pi has developed through the years into a fairly powerful single-board computer, it is probably not appropriate to run a full development environment and run the Python application being developed all on the same Rasp Pi

VS Code is an editor first and foremost. Instead of installing it on a Raspberry Pi with a keyboard, mouse, and video screen attached [2], you can deploy the VS Code tools for remote debugging. For this exercise, I installed VS Code on a workstation running Ubuntu 20.04; then, VS Code installed its headless server component designed for the ARM7 processor on the Raspberry Pi (Figure 1). This installation setup allows you to write and modify code from a local workstation and run and test the code on a Raspberry Pi (see the "Materials" box).

Figure 1: Instead of installing VS Code on the Raspberry Pi, I opted for a workstation installation with a connection to the Pi.

Materials

  • Workstation: 64-bit Ubuntu 20.04.1 LTS
  • Visual Studio Code: version 1.47.3
  • Pi3B+, 8GB SD card
  • Raspberry Pi OS (previously called Raspbian) 2020-05-27-raspios-buster-lite

Preparation

The first exercise in creating a development environment with VS Code is to establish an SSH connection from the Ubuntu workstation to the Raspberry Pi and configure it so that no password is required.

To generate a public and private public key infrastructure (PKI) key pair and transfer the public key to the Raspberry Pi host (Figure 2), issue the following commands from a command-line interface (CLI) on the workstation:

ssh-keygen <optional passphrase>
ssh-copy-id -i ~/.ssh/id_rsa.pub pi@<Pi IP Address>
Figure 2: Output from an SSH key generation command, retaining default file names.

Being security conscious, best practice is to include a passphrase when prompted. You should retain the file defaults, unless you have the knowledge to customize the configuration.

The command

ssh-copy-id -i ~/.ssh/<mykey> <user>@<host>

logs in to the Raspberry Pi, copies the public key file, and configures the key in the authorized_keys file to grant access. The copying may ask for a password or other authentication to connect with the Pi.

After the SSH configuration, the first time you log in requires you to supply a password. After that, SSH connections should be made without password prompting. You will know you are successful when you enter

ssh pi@<Pi IP Address>

and it drops you into a remote prompt without the need for a password.

Now that you have a Raspberry Pi SSH connection working without password prompting, you need to tailor the Pi for a development environment. Some additional software needs to be added so that it is prepared to support the changes that VS Code is going to make to establish a remote connection to the Pi. The following commands entered from the CLI on the Raspberry Pi adds the needed software:

sudo apt update
sudo apt upgrade
sudo apt install git python-pip python3-pip

The update and upgrade commands should always precede any Raspberry Pi software install requests. The commands refresh the environment and prepare it for the new installs.

The apt install command loads the Git distributed version control system and pip, the package manager for Python packages for the Python 2 and 3 environments. Packages contain the files needed for a module, which is a Python code library. If VS Code wants to install Python software, it is going to call pip to make it happen.

Host Workstation Installation

On the Ubuntu workstation, you should install VS Code from the Ubuntu Software Center. For Ubuntu 20.04, the Software Center will list two versions of VS Code: Visual Studio Code and Visual Studio Code Insiders. The description provided in the window for both are identical, so what is the difference?

Visual Studio Code is the stable version, whereas Visual Studio Code Insiders is the daily release with the most recent code pushes. The Insider builds have new features, bug fixes, and other recently closed issues. If you like working on the edge of software development, consider a side-by-side install (i.e., Insiders installed next to the stable build), so you can use either version independently.

If using the latest releases of VS Code appeals to you, you might want to consider removing the Remote-SSH extension and replacing it with the Remote-SSH (Nightly) extension. The Remote-SSH extension lets you use any remote machine with an SSH server as your development environment. The nightly build version of the extension provides the developer early feedback and testing. This extension works best with VS Code Insiders. You must uninstall the stable version of the extension before using the nightly version. Be aware that bleeding edge builds may lead to the occasional broken build.

After firing up VS Code, you will see a welcome screen. Typically, I would start by exploring all the options of the VS Code interface, but I will not use that approach for the moment and pick it up later when VS Code is connected to the Raspberry Pi. For now, I will consider how to configure the application environment for Python.

Some changes are needed in the VS Code installation before proceeding. To begin, at the bottom of the left-hand vertical Activity Bar, select Extensions (the Tetris, or falling block, icon). Extensions add features to VS Code, and you can install those you need or uninstall those you don't require. Recall that the goal is to create a development environment for Python coding on the Raspberry Pi.

In the Extensions Search field, search for extensions that have "python" in the name, and click the Install button for ms-python.python to install the Microsoft Python extension (Figure 3). For a development environment, you should add support for Python code formatting (discussed in greater detail later) by installing the Python-autopep8 (himanoa.python-autopep8) extension.

Figure 3: The VS Code extension trifecta for Python support.

Recall that you did some configuration work earlier on the Raspberry Pi to enable SSH, so you should add that feature to VS Code by installing the Remote-SSH (ms-vscode-remote-ssh) extension.

Remote Pi Installation

VS Code is now ready to reach out and connect to the Raspberry Pi. The remote connection from the Ubuntu workstation to the Pi must be configured to support the SSH connection without a password. From the VS Code console, press F1; in the search field, enter remote and select Remote-SSH: Add New SSH Host.

The prompt displays the standard command format ssh hello@microsoft.com to make an SSH connection. Enter the connection details for the Raspberry Pi. Now, press the F1 key again and select Remote-SSH: Connect to Host; the entry you made for the Pi connection is displayed, so select that item.

If all goes well, VS Code opens another console. At the bottom of the screen it displays the connection details and indicates that it is busy using the connection to bring the Raspberry Pi into the VS Code fold (Figure 4). When complete, the console will remain, and VS Code will be ready for you to program on your Pi (Figure 5).

Figure 4: VS Code sets up the Raspberry Pi to communicate with the host remotely over SSH.
Figure 5: The VS Code Welcome page. This article is based on version 47. At the time of publication, the software had advanced to version 51. The instructions are still valid for the Raspberry Pi VSC install, but the "Start" page has changed in the most recent version.

The Suspended Tour

Now that VS Code is installed on the Raspberry Pi development environment, I'll review the interface. Instead of describing the interface options (Figure 6), I will introduce them by performing some tasks to condition the Pi development environment.

Figure 6: VS Code workspace: (A) Activity Bar, (B) Sidebar, (C) Menubar, (D, E) Panels, (F) Explorer view, (G) Editor workspace, (H) Run arrow, (I) Outline view.

In the interface, the Activity Bar (A), the vertical bar on the left side of the screen, contains the icons for the various views (from the top): Explorer, Search, Source Control, Run, Remote Explorer, and Extensions. From the Explorer view of the Welcome page, select Open Folder, choose the directory /home/pi, and press the OK button.

VS Code opens the folder and creates a panel in the workspace (B), which is basically just a collection of related panels. The Explorer view displays the files and folders for the current project workspace, along with any currently open editors.

The left panel of the workspace is a list of the Raspberry Pi's home directory. It also shows how many files have been modified and not yet saved. The .vscode-server directory is where VS Code for the remote Pi install was created.

From the main menubar (C), select Terminal | New Terminal to open a panel (D) at the bottom of the workspace that displays a terminal window for the Raspberry Pi. The plus (+) icon in the terminal panel (E) enables you to open additional terminal windows, the drop-down lets you choose between the named terminal windows, and the trash can icon closes the terminal.

From the Explorer view, create a new folder named python_scripts from the icon options and then create a file named hello_world.py (F). An Editor panel opens in the workspace (G), where you can modify, add, and delete file content. In the editor, add the line

print("Hello World")

to create a simple line of Python code that will print Hello World when the script is run. Use the Save icon on the left in the Open Editors line to save the file.

The .py extension has significance for VS Code. The extension is the trigger for the application to customize the environment for the programming language – in this example, Python.

After saving the file, VS Code opens a notification message about recommended extensions for Python (Figure 7). The application indicates that it could use a little support on the Raspberry Pi for Python programming. Ignore the notification message by closing the message window. Instead of letting VS Code do the preparation, you can install the recommended Python extensions manually.

Figure 7: Although you installed Python packages on the Ubuntu host, the Raspberry Pi needs Python support, too.

From the Activity Bar, select the Extensions view, which lists all of the installed extensions. This view also shows you which extensions need to be updated and lets you update them. The workspace on the left will indicate that no extensions are found on the SSH: <IP Address> connection, because the extensions that were installed to this point were all on the Ubuntu VS Code workstation.

The goal has been to create a Python development environment for the Raspberry Pi. In the Extensions view, enter python in the Search Extensions in Marketplace field. The search results will display Python extensions that can be installed to the SSH connection. Select the Python (Microsoft) extension to install (Figure 8). Recall that you installed this same extension on the VS Code host workstation.

Figure 8: The results of a search for Python extensions available for installation.

After a brief installation interlude of flashing dots, a Reload Required button appears. Now you can reload VS Code by pressing the button to enable this extension on the Raspberry Pi. The screen refreshes the Extensions workspace panel on the left and indicates that the Python extension has been installed.

To see what this manually loaded VS Code recommended extension does for the development environment, select the Explorer view from the Activity Bar and open the Python hello_world.py file created earlier. If any terminal windows are open in the lower portion of the workspace, select the trash can to close them. VS Code is constantly looking to tailor the environment, so you might also have a notification message (discussed later). At some point, the environment will be stable and the messages will stop. Ignore them for now, but don't close the message.

In the upper right-hand corner of the Editor workspace (Figure 6, H), select the green arrow icon to run the Python file. A terminal panel then opens in the lower right workspace and the Python script is executed, displaying the Hello World output.

In addition to the extensions notification message received earlier, you will also get a notice that autopep8 (which formats Python code to conform to PEP 8 coding conventions [3]) is missing from the development environment on the Raspberry Pi. VS Code attempts to help you by indicating missing software components that aid Python code development.

Go ahead and use the Install button in the notification message to install the pyline Python linter package. Earlier in the tutorial, when preparing the Raspberry Pi environment, you installed Pip, which VS Code uses to install the required Python packages on the Pi. In the terminal panel, feedback is displayed as the package is installed. For now, close the notification about autopep8. After some additional instruction you will be better prepared to deal with that notification message.

So far, the VS Code Remote SSH connection (Figure 6, I) to the Raspberry Pi has provided a graphical file and folder listing, an editor for modifying code, the ability to add or delete Python scripts, and a terminal panel that allows you to run the code. It also informs you when it discovers missing Python packages. VS Code also lets you install Python extensions and packages. As a huckster on a television commercial would say, "but wait, there is more!"

Tour Continued

In the Editor panel (Figure 6, G) use the mouse to select all lines of code, then right-click for the command context menu and choose Run Selection/Line in Python Terminal. A Python terminal opens in the bottom panel and runs the code selection. Recall the Python programming language itself has its own terminal or console. VS Code lets you to take a portion of the code from the editor and run it in the Python terminal. Click the trash can in the terminal panel when you are done examining it.

One of the difficulties experienced by professional and casual code writers alike is code formatting. Programming rules help make code easier to read and understand. Python is particularly sensitive to formatting because indentations and white spaces affect code. VS Code provides support through extensions for automatically applying formatting to Python code.

From the Editor workspace, add an octothorpe, another term for the hash sign (#), to the end line of code in the hello_world.py file,

print("Hello World") #

and save the file. The octothorpe triggers the notification regarding PEP 8 formatting. Select Yes in the notification message to apply the changes. Now that Python on the Raspberry Pi has the package it requires, you need to configure VS Code to use it.

Style guides are all about code consistency. The guidelines are intended to improve the readability of code and make it consistent across a wide spectrum of Python code. VS Code has other formatters, but for this exercise, I'll explore PEP 8.

To implement the PEP 8 style guide, select the Extensions view from the Activity Bar and search for autopep8. Use the Install to SSH button to install the Python-autopep8 extension and press the Reload Required button to complete the PEP 8 install on the Raspberry Pi.

From the main menubar (Figure 6, C) select File | Preferences | Settings. In the search bar, enter python formatting. From the search returns, scroll down to Python>Formatting:Provider and confirm that autopep8 is selected. In the search bar, enter format on save as the search criterion. Put a checkmark beside the setting Editor:Format on Save. Now VS Code will use the PEP 8 style guide before a file is saved.

To take the PEP 8 formatter for a test drive, select the Explorer view in the Activity Bar and open the Python file hello_world.py you created earlier. Modify the line containing the print command as follows,

import math,os,time
print("hello world")#this is a comment

and save the file.

If Python PEP 8 support is functioning correctly, the script will change after the save (Figure 9). For example, the import statement is divided across multiple lines and the comment line will have some spaces inserted, as per the PEP 8 rules for Python code.

Figure 9: Python code before and after formatting, courtesy of the Python-autopep8 extension.

Lesser Detail

To wrap up the VS Code console tour, I'll describe some of the Activity Bar items not used. The magnifying glass icon represents the Search view, in which you can search for and optionally replace content within the current editor or across multiple files.

The Source Control view (the source tree icon) provides access to source control software that tracks and manages changes to code. Recall when first preparing the Raspberry Pi environment that you installed the Git software package. Git is the most commonly used version control system today. VS Code provides support for Git through the Source Control view.

If Git is established in the Source Control environment and the project being worked on is in a Git repository, then the view will show relevant Git information, such as how many files have been changed and which files have been changed and staged, and will even commit your changes.

Source Control is important even to the amateur developer, and it can be relied on as a form of code backup. After you have spent your time writing the code, it would be nice for it to stick around if your Raspberry Pi development environment were to fail. If Git is using a repository, then the code is safe.

The Run view (an arrow with a bug), the final Activity Bar item to be mentioned, establishes a Python debugging environment. When you select the Run view icon, the debugger needs the launch.json configuration file. The file will be displayed with some default configurations. A .vscode folder is created to hold this file.

VS Code debugging allows you to step through code line by line and fix problems. To stop code at a specific point, you can establish breakpoints and conditional breakpoints. Debugging also enables log points for coding [4].

Summary

VS Code provides a development environment that will make you a more efficient Raspberry Pi coder by taking over some of the tasks and freeing time for you to focus on what is important – writing code. Until next time, keep your Pi in that creative oven.

The Author

Sean D. Conway (the D in the name is to keep his mail from being delivered to his neighbor with the same name) is a retired IT security specialist for a national telecommunication company. In addition to designing, installing, maintaining, and securing computer systems in a telecommunications environment, his 40-year career has spanned engineering ground-based aviation navigation and communications electronic systems and teaching data communication in a community college.