My question is: How do I configure the pi so that i can plug it back in, it boots up itself and runs the program without having to use ssh or a keyboard and monitor to login.
You don't have to do anything to the RPi to have it start (boot) when power is connected - this is the way it works!
You can use cron
to start a Python program upon startup - this is very simple. Use the terminal (via SSH if necessary) and Command Line Interface (CLI) as follows:
1. Take care of two (2) prerequisites
Once you are logged in as default user pi
, you are presented with a terminal screen in the bash
shell. You will see a prompt similar to the one shown below indicating where to begin your input.
pi@raspberrypi4b:~ $
You must know the location of your program - full path specification; e.g. /home/pi/MyPythonProgram.py
Your program must be marked as executable; you can ensure the program is executable with this command:
pi@raspberrypi4b:~ $ chmod a+x /home/pi/MyPythonProgram.py
2. Open your crontab
for editing:
At the bash
prompt (pi@raspberrypi4b:~ $
), open your crontab
for editing (choose nano
as your default editor if asked):
$ crontab -e
Your default crontab
will open in the nano
editor.
3. "Schedule" your program to start each time the RPi boots:
Move the "insertion point" in nano
just below any existing text in crontab
, and type the following:
@reboot (sleep 20; /home/pi/MyPythonProgram.py) >> /home/pi/logmyprogram.txt 2>&1
Here's what this does:
@reboot
simply instructs cron
to execute the following commands each time the system boots.
sleep 20
waits 20 seconds after cron
is started before it starts your program
- your program (assumed to be
/home/pi/MyPythonProgram.py
) is started
- any output or errors (
stdout
or stderr
, 2>&1
) from your program are re-directed (>>
) to a file: /home/pi/logmyprogram.txt
sleep
and the redirect are often useful in running cron
jobs. sleep
provides additional time for all system resources to get started (e.g. networking services). redirect (>>
) is useful as your interactive shell won't be available to receive any output or error messages - instead, they will be written to the logfile you choose.
4. Test
Reboot your system (sudo reboot
at the shell prompt). Review the logfile for any mesages.