跳到主要内容

VS Code Remote Development on Raspberry Pi via SSH

This guide explains how to set up Visual Studio Code (VS Code) for remote development on a Raspberry Pi using SSH. This setup allows you to develop IoT and embedded projects directly on the Raspberry Pi while maintaining the comfort of your local development environment.

VS Code Remote Development on Raspberry Pi

Overview

Remote development on Raspberry Pi offers several advantages:

  • Direct hardware access: Work with GPIO, sensors, and peripherals directly
  • Consistent environment: Use your local VS Code setup with Pi's resources
  • Efficient development: No need to transfer files manually
  • Real-time testing: Test embedded applications in the target environment

Prerequisites

  • Raspberry Pi with Raspberry Pi OS installed
  • Local machine with VS Code
  • Network connection between both devices
  • Basic familiarity with SSH and command line

1. Install VS Code and Extensions

1.1 Install VS Code on Local Machine

Download and install Visual Studio Code from the official website.

1.2 Install Remote Development Extensions

Install the Remote Development extension pack:

  1. Open VS Code
  2. Click on the Extensions view icon on the sidebar (Ctrl+Shift+X)
  3. Search for Remote Development
  4. Install the extension pack by Microsoft

This pack includes:

  • Remote - SSH
  • Remote - Containers
  • Remote - WSL

1.3 Alternative: Install Remote - SSH Only

If you only need SSH functionality:

  1. Search for Remote - SSH
  2. Install the extension by Microsoft

2. Configure SSH on Raspberry Pi

2.1 Enable SSH Service

SSH is typically enabled by default on newer Raspberry Pi OS installations. To verify or enable it:

Method 1: Using raspi-config (Recommended)

# Open Raspberry Pi configuration tool
sudo raspi-config

# Navigate: Interfacing Options > SSH > Enable
# Select "Yes" to enable SSH
# Finish and reboot if prompted

Method 2: Using systemctl

# Enable SSH service
sudo systemctl enable ssh

# Start SSH service
sudo systemctl start ssh

# Check SSH status
sudo systemctl status ssh

Method 3: Enable SSH via desktop

  1. Go to Raspberry Pi Configuration from the Preferences menu
  2. Navigate to the Interfaces tab
  3. Enable SSH
  4. Click OK and reboot if prompted
# Edit SSH configuration
sudo nano /etc/ssh/sshd_config

Recommended settings:

# Change default port (optional)
# Port 2222

# Disable root login
PermitRootLogin no

# Enable public key authentication
PubkeyAuthentication yes

# Keep connections alive
ClientAliveInterval 60
ClientAliveCountMax 3

# Limit login attempts
MaxAuthTries 3

Apply changes:

sudo systemctl restart ssh

3. Network Configuration

3.1 Find Raspberry Pi IP Address

Method 1: Using hostname command

# Get IP address
hostname -I

# Get detailed network information
ip addr show

Method 2: Using ifconfig

ifconfig

Method 3: Check router's admin panel

  • Access your router's web interface
  • Look for connected devices
  • Find your Raspberry Pi in the device list

For consistent connections, set a static IP address:

# Edit dhcpcd configuration
sudo nano /etc/dhcpcd.conf

Add at the end of the file:

# Static IP configuration
interface eth0 # or wlan0 for WiFi
static ip_address=192.168.1.100/24
static routers=192.168.1.1
static domain_name_servers=192.168.1.1 8.8.8.8

Apply changes:

sudo systemctl restart dhcpcd

3.3 Configure Firewall (If Enabled)

# Check if ufw is active
sudo ufw status

# Allow SSH through firewall
sudo ufw allow ssh

# For custom SSH port
sudo ufw allow 2222/tcp

4. SSH Key Setup

4.1 Generate SSH Key Pair (Local Machine)

On Windows:

# Open Command Prompt or PowerShell
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

# Follow prompts:
# Enter file: Press Enter for default (C:\Users\<username>\.ssh\id_rsa)
# Enter passphrase: Optional but recommended
# Confirm passphrase

On Linux/macOS:

# Generate SSH key pair
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

# Follow prompts:
# Enter file: Press Enter for default (~/.ssh/id_rsa)
# Enter passphrase: Optional but recommended
# Confirm passphrase

4.2 Copy Public Key to Raspberry Pi

Method 1: Using ssh-copy-id (Linux/macOS)

# Copy public key to Raspberry Pi
ssh-copy-id pi@192.168.1.100

# Replace with your Pi's username and IP
ssh-copy-id <raspberry_pi_username>@<raspberry_pi_ip>

Method 2: Manual Copy (All Platforms)

Display your public key:

# Windows
type C:\Users\<username>\.ssh\id_rsa.pub

# Linux/macOS
cat ~/.ssh/id_rsa.pub

Copy the displayed key, then:

# Connect to Raspberry Pi
ssh pi@192.168.1.100

# Create .ssh directory (if it doesn't exist)
mkdir -p ~/.ssh

# Edit authorized_keys file
nano ~/.ssh/authorized_keys

# Paste your public key into this file
# Save and exit (Ctrl+X, Y, Enter)

# Set proper permissions
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
Important Note

authorized_keys is a fixed filename. If you have multiple keys, save all of them in this file, each on a separate line.

4.3 Test SSH Connection

# Test passwordless SSH connection
ssh pi@192.168.1.100

# Should connect without asking for password
# Exit the session
exit

5. Configure VS Code SSH Connection

5.1 Connect via Command Palette

  1. Open VS Code
  2. Press Ctrl+Shift+P (Cmd+Shift+P on macOS)
  3. Type Remote-SSH: Connect to Host...
  4. Enter: pi@192.168.1.100 (replace with your Pi's details)
  5. Select the platform: Linux
  6. VS Code will install the server components automatically

5.2 Create SSH Configuration File

Create an SSH config file for easier connection management:

File locations:

  • Windows: C:\Users\<username>\.ssh\config
  • Linux/macOS: ~/.ssh/config

Example configuration:

# Raspberry Pi Development
Host raspberry_pi
HostName 192.168.1.100
User pi
Port 22
IdentityFile ~/.ssh/id_rsa
ServerAliveInterval 60
ServerAliveCountMax 3

# Multiple Pi setup example
Host pi-zero
HostName 192.168.1.101
User pi
Port 22

Host pi-4
HostName 192.168.1.102
User pi
Port 22

For Windows, use full paths:

Host raspberry_pi
HostName 192.168.1.100
User pi
IdentityFile C:\Users\<username>\.ssh\id_rsa

5.3 Connect Using SSH Config

  1. Open Command Palette (Ctrl+Shift+P)
  2. Type Remote-SSH: Connect to Host...
  3. Select raspberry_pi from the list
  4. VS Code will connect using your saved configuration

6. VS Code Remote Development on Pi

6.1 First Connection Setup

  1. VS Code will automatically install the VS Code Server on your Pi
  2. Wait for the installation to complete (may take several minutes)
  3. You'll see "SSH: raspberry_pi" in the bottom-left corner when connected

6.2 Working with Raspberry Pi Files

# Open a folder on the Pi
Ctrl+K Ctrl+O

# Open terminal on Raspberry Pi
Ctrl+` (backtick)

# File explorer shows Pi's file system
# All extensions run on the Raspberry Pi

6.3 Install Extensions for Pi Development

Install these extensions on the remote (Raspberry Pi) side:

Essential Extensions:

  • Python - For Python development
  • C/C++ - For compiled languages
  • GitLens - Enhanced Git capabilities
  • Bracket Pair Colorizer - Better code readability

IoT/Embedded Specific:

  • PlatformIO IDE - For embedded development
  • Arduino - Arduino development support
  • Circuit Python - MicroPython support

Installation steps:

  1. Go to Extensions view (Ctrl+Shift+X)
  2. Look for "SSH: raspberry_pi - Installed" section
  3. Install extensions in the remote section

6.4 Raspberry Pi Specific Development

GPIO and Hardware Access:

# Example: LED control with RPi.GPIO
import RPi.GPIO as GPIO
import time

# Setup
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)

# Blink LED
for i in range(10):
GPIO.output(18, GPIO.HIGH)
time.sleep(0.5)
GPIO.output(18, GPIO.LOW)
time.sleep(0.5)

# Cleanup
GPIO.cleanup()

Install common Pi libraries:

# Python libraries for Raspberry Pi
pip install RPi.GPIO
pip install gpiozero
pip install adafruit-circuitpython-*
pip install w1thermsensor

# For camera module
pip install picamera2

7. Development Workflow Examples

7.1 Python IoT Project Setup

# Create project directory
mkdir ~/my_iot_project
cd ~/my_iot_project

# Create virtual environment
python -m venv venv
source venv/bin/activate

# Install dependencies
pip install RPi.GPIO requests flask

# Create requirements file
pip freeze > requirements.txt

7.2 GPIO Programming

# sensor_reader.py
from gpiozero import MotionSensor, LED
from signal import pause

# Setup components
pir = MotionSensor(4)
led = LED(18)

# Event handlers
def motion_detected():
print("Motion detected!")
led.on()

def no_motion():
print("Motion stopped")
led.off()

# Assign events
pir.when_motion = motion_detected
pir.when_no_motion = no_motion

# Keep program running
pause()

7.3 Web Server for IoT Control

# app.py - Simple Flask web server
from flask import Flask, render_template, request
from gpiozero import LED

app = Flask(__name__)
led = LED(18)

@app.route('/')
def index():
return '''
<h1>Raspberry Pi LED Control</h1>
<a href="/led/on"><button>Turn ON</button></a>
<a href="/led/off"><button>Turn OFF</button></a>
'''

@app.route('/led/<state>')
def led_control(state):
if state == 'on':
led.on()
return "LED is ON"
elif state == 'off':
led.off()
return "LED is OFF"

if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)

8. Port Forwarding for Web Development

8.1 Forward Ports from Pi to Local Machine

  1. Open Command Palette (Ctrl+Shift+P)
  2. Type Remote-SSH: Forward Port from Active Host
  3. Enter port number (e.g., 5000 for Flask)
  4. Access via http://localhost:5000 on your local machine

8.2 Automatic Port Forwarding

VS Code can automatically detect and forward common development ports:

  • Port 3000 (React, Node.js)
  • Port 5000 (Flask)
  • Port 8000 (Django, HTTP server)
  • Port 8080 (Alternative HTTP)

9. Troubleshooting

9.1 Connection Issues

"Connection Refused" Error

# Check SSH service on Pi
sudo systemctl status ssh

# Restart SSH service
sudo systemctl restart ssh

# Check if SSH port is open
sudo netstat -tlnp | grep :22

"Permission Denied" Error

# Check SSH key permissions on local machine
ls -la ~/.ssh/

# Fix permissions on Pi
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

"Host Key Verification Failed"

# Remove old host key
ssh-keygen -R 192.168.1.100

# Connect again to accept new key
ssh pi@192.168.1.100

9.2 Performance Issues

Slow Connection

# Add to SSH config for better performance
Host raspberry_pi
HostName 192.168.1.100
User pi
Compression yes
TCPKeepAlive yes
ServerAliveInterval 60

VS Code Server Issues

# Remove VS Code Server files on Pi
rm -rf ~/.vscode-server

# Reconnect to reinstall

9.3 Hardware-Specific Issues

GPIO Permission Errors

# Add user to gpio group
sudo usermod -a -G gpio $USER

# For i2c and spi
sudo usermod -a -G i2c,spi,gpio $USER

# Logout and login again

Camera Module Issues

# Enable camera interface
sudo raspi-config
# Navigate: Interfacing Options > Camera > Enable

# Test camera
raspistill -o test.jpg

10. Best Practices

10.1 Security Best Practices

  1. Use SSH keys instead of passwords
  2. Change default SSH port
  3. Keep Pi OS updated
  4. Use firewall when needed
  5. Regular security audits
# Update Raspberry Pi OS
sudo apt update && sudo apt upgrade -y

# Check for security updates
sudo unattended-upgrade -d

10.2 Development Best Practices

  1. Use virtual environments for Python projects
  2. Version control with Git
  3. Regular backups of important projects
  4. Document hardware connections
  5. Use proper error handling in embedded code

10.3 Hardware Safety

  1. Always shutdown Pi properly
  2. Use appropriate resistors with LEDs
  3. Check voltage levels before connections
  4. Use proper ESD precautions
# Proper shutdown
sudo shutdown -h now

# Restart
sudo reboot

11. Advanced Features

11.1 Multiple Raspberry Pi Management

# SSH config for multiple Pis
Host pi-livingroom
HostName 192.168.1.100
User pi

Host pi-garage
HostName 192.168.1.101
User pi

Host pi-garden
HostName 192.168.1.102
User pi

11.2 Cross-Compilation Setup

For ARM development on x86 machines:

# Install cross-compilation tools
sudo apt install gcc-arm-linux-gnueabihf

# Configure for Pi Zero (ARMv6)
export CC=arm-linux-gnueabihf-gcc
export CXX=arm-linux-gnueabihf-g++

11.3 Docker on Raspberry Pi

# Install Docker on Pi
curl -fsSL https://get.docker.com -o get-docker.sh
sh get-docker.sh

# Add user to docker group
sudo usermod -aG docker pi

# Test Docker
docker run hello-world

Resources

Pro Tips
  • Use a high-quality SD card (Class 10 or better) for better performance
  • Set up SSH key-based authentication for security
  • Use VS Code's integrated terminal for Pi-specific commands
  • Enable I2C/SPI/Camera through raspi-config before using them
  • Consider using a USB-to-Ethernet adapter for more stable connections
Performance Note

Raspberry Pi 4 with 4GB+ RAM provides the best experience for VS Code remote development. Older models may be slower but still functional.