2

I have written a small python script that plays a track after the press of a button (and ignores further button presses until the track has completed). The script works perfectly fine when started from terminal, but I simply cannot find a way to make it start on reboot with cron. Here is the script hoelderlinbutton.py:

import pygame
pygame.init()
pygame.mixer.init()
music = pygame.mixer.music.load("/home/pi/Hoelderlin.mp3")
from signal import pause
from gpiozero import Button
def on_press ():
   if pygame.mixer.music.get_busy() == False:
      pygame.mixer.music.play()
button = Button(2)
button.when_pressed = on_press
pause()

The relevant line in crontab -e is:

@reboot /usr/bin/python3 /home/pi/hoelderlinbutton.py

Upon reboot, nothing happens after pressing the button. I've activated cron logging (Where do Cron error message go?) but the log indicates that the script was executed. I tried to log for any errors from the script by changing the line in crontab to this:

@reboot /usr/bin/python3 /home/pi/hoelderlinbutton.py > /home/pi/logs/backup.log 2>&1

But the created log file is empty.

I then experimented, based on various hints and ideas from previous posts and answers by:

But none of this got me anywhere. I'm a little out of my depth here, but I believe that some limitation in the crontab environment prevents the actual playing of the track (or perhaps causes an issue with the GPIO). Any ideas what else I can try?

1
  • 1
    Start the program from the GUI autostart not from Cron. sudo nano /etc/xdg/lxsession/LXDE-pi/autostart
    – Dougie
    Jul 6 at 21:43
0

Yes, Dougie's proposal works -- I wish I had asked earlier! I removed the crontab entries and instead edited the autostart configuration with

sudo nano /etc/xdg/lxsession/LXDE-pi/autostart

and then added

@/usr/bin/python /home/pi/hoelderlibutton.py

in the second-to-last line. And then all is working perfectly! In the longer term, I'd love to understand why it did not function in cron -- but for now I'm just happy to have this working. Thanks, Dougie!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.