How to Run a Raspberry Pi Program on Startup
The Raspberry Pi is a great single board computer, but like most computers, its functions rely mostly on human input. That means whenever you start up (or boot) your computer, it waits for your input to run programs. That's great, but how do we get our programs to run automatically whenever the computer boots?
Linux is a fairly complex operating system, and as such, there are often multiple ways to perform any one action. To get a program to run on boot, we will cover several ways. To show some example programs, we will blink an LED and turn the Raspberry Pi into a clock.
While using the Raspberry Pi as a clock might seem like overkill, feel free to substitute your own program or script instead. You are also welcome to use the example code as the basis for your own dashboard (e.g. show the local forecast when you wake up, your personal server uptime, number of days left until your favorite show, etc.) or electronics project.
Before adding your program to any startup script, it's extremely important that you test it first on its own! Run it with just the
python command to make sure there are no problems with your program. It's much harder to track down bugs in your code when it runs as part of the boot process.
The three methods covered in this tutorial are:
- rc.local - Likely the easiest and simplest way to get your program to run on boot. The downside is that tasks started with rc.local happen before the X windows system starts, which means you will not have access to graphical user interface (GUI) elements.
- autostart - Used to automatically run your programs once LXDE (graphical desktop environment used by Raspbian) starts. It's slightly more complicated than rc.local, but it lets you run programs that require graphical elements.
- systemd - The new and popular way to automatically start programs in Linux. It is definitely the most complicated of the three, but it allows you to run before LXDE starts, wait until you have access to other processes (e.g. networking, graphical desktop), or simply restart your program over and over again until it works. As such, it is a robust way to create and manage services that run in the background.
At a bare minimum, you will need a Raspberry Pi, SD card, and power supply for this tutorial. If you plan to make a dashboard (or clock, as given by the example code in the next section), you will need a monitor and keyboard for your Pi. If you would like a full desktop setup, we recommend the following:
If you aren't familiar with the following concepts, we recommend checking out these tutorials before continuing: