How to Auto Start Programs on Raspberry Pi

Raspberry Pi is a widely used single-board computer, but it usually requires an SSH connection to the Pi and manual initiation of programs. For users seeking convenient startup options, there are three common methods: adding startup items in /etc/rc.local, adding desktop startup applications in ~/.config/autostart, and adding service items in /etc/init.d/. In this article, TechSparks will walk you through how to perform these operations.

Table of Contents

Editing Test Program

Before setting up automatic startup on Raspberry Pi, it’s advisable to write a test program. We suggest creating a program that blinks an LED using GPIO control, as hardware operations provide a visual indication of whether the program is running correctly at startup. Hardware operations are more straightforward for verifying the program’s status compared to console output.

Alternatively, you can refer to my test program. It’s a simple Python program that continuously sends the string “123” via UDP to a specified host:

				
					#!/usr/bin/python
import socket
import time
# Set the target host and port
HOST = '192.168.191.1'
PORT = 9999
# Create a UDP socket object
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Attempt to connect to the specified host and port
server.connect((HOST, PORT))
# String data to be sent
data = '123'
try:
    # In an infinite loop, continuously send encoded data and wait 1 second after each send
    while True:
        server.sendall(data.encode(encoding='utf-8'))
        time.sleep(1)
# Capture exceptions and print error messages
except Exception as e:
    print(f"Error in sending data: {e}")
# Close the socket connection regardless of whether an exception occurred
finally:
    server.close()
				
			

Execute the following command to make the Auto_Start_Demo.py file executable:

				
					sudo chmod 755 Auto_Start_Demo.py
				
			

On your PC, write a Python program to receive UDP data sent from the Raspberry Pi:

				
					import socket
# Set the host and port
HOST = '192.168.191.1'
PORT = 9999
bufsize = 1024  # Specify buffer size
# Create a UDP socket object and bind it to the specified host and port
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.bind((HOST, PORT))
try:
    while True:
        # Receive data and sender's address information
        data, addr = server.recvfrom(bufsize)
        # If a termination signal is received (length is 1, content is 1), exit the loop
        if len(data) == 1 and data[0] == 1:
            print("Received termination signal. Exiting.")
            break
        # Decode the received data
        decoded_data = data.decode(encoding='utf-8')
        # Print the received data and sender's address information
        print(f"Received data from {addr}: {decoded_data}")
# Capture exceptions and print error messages
except Exception as e:
    print(f"Error in receiving data: {e}")
# Close the socket connection regardless of whether an exception occurred
finally:
    server.close()
				
			

Method 1: Add Startup Items in /etc/rc.local

While it is possible to achieve Raspberry Pi autostart by editing the /etc/rc.local file, this method is not always reliable. After multiple attempts, we found that using the reboot command has a relatively high success rate, although in some cases, it may result in two identical processes. Follow these steps:

  1. Edit the rc.local file:
				
					sudo vim /etc/rc.local
				
			
  1. Add the following statement above exit 0:
				
					/home/pi/Auto_Start_Demo.py &
				
			
This statement indicates running the Auto_Start_Demo.py file and uses the & symbol to run it in the background.
  1. Reboot the Raspberry Pi:
				
					sudo reboot

				
			
Method 1

Method 2: Using Desktop Applications

While this method is typically used for desktop applications’ autostart, it can sometimes successfully trigger the execution of custom commands. Follow these steps:

  1. Navigate to the .config directory in the user’s home directory:
				
					cd ~/.config
				
			
  1. Create the autostart directory if it doesn’t exist:
				
					mkdir -p autostart
				
			
  1. Create a .desktop file in the autostart directory:
				
					nano autostart/Auto_Start_Test.desktop
				
			
  1. Edit the content of the .desktop file:
				
					[Desktop Entry]
Name=Auto Start Demo
Comment=Starts the Auto_Start_Demo.py script on login
Type=Application
Exec=/usr/bin/python3 /home/pi/Auto_Start_Demo.py &
				
			
  1. Reboot the Raspberry Pi:
				
					sudo reboot

				
			

Method 3: Add Service Items in /etc/init.d/

To achieve program autostart on the Raspberry Pi, you can create a service script. Here are the steps to create and configure the service script:

  1. Create the service script:
				
					sudo nano /etc/init.d/Auto_Start_Test
				
			
  1. Add the following content to the file:
				
					#!/bin/bash
### BEGIN INIT INFO
# Provides: Auto_Start_Test
# Required-Start: $remote_fs
# Required-Stop: $remote_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Auto Start Test
# Description: This service is used to test auto start service
### END INIT INFO
case "$1" in
    start)
        echo "Starting Auto_Start_Test service"
        /home/pi/Auto_Start_Demo.py&
        ;;
    stop)
        echo "Stopping Auto_Start_Test service"
        pkill -f /home/pi/Auto_Start_Demo.py
        exit 1
        ;;
    *)
        echo "Usage: service Auto_Start_Test start|stop"
        exit 1
        ;;
esac
exit 0

				
			
  1. Set permissions:
				
					sudo chmod 755 /etc/init.d/Auto_Start_Test
				
			
  1. Add it to the startup items:
				
					sudo update-rc.d Auto_Start_Test defaults
				
			
  1. Test the service:
				
					sudo service Auto_Start_Test start
sudo service Auto_Start_Test stop
				
			
  1. Reboot the Raspberry Pi:
				
					sudo reboot
				
			

Ending

Among these three Raspberry Pi autostart methods, editing /etc/rc.local and setting up through desktop applications are relatively simple but may not yield desirable results. It is recommended to use the third method for setting up autostart.

You Might Be Interested

raspberry pi autostart
How to Auto Start Programs on Raspberry Pi

Automating program startup on the Raspberry Pi can be achieved through various methods. Editing the “/etc/rc.local” file or using desktop applications, while simpler, may not

raspberry pi
What is Raspberry Pi?

Raspberry Pi, a revolutionary single-board computer introduced by the Raspberry Pi Foundation, has become a global sensation, initially designed for educational purposes. With its integrated

Scroll to Top