Search code examples
pythonpygameraspberry-pi3gpioautostart

Raspberry pi python3 script with pygame and gpio autostart at boot


I am trying to autostart this python script at boot:

import RPi.GPIO as GPIO
import time
import pygame


GPIO.setmode(GPIO.BCM)

GPIO.setup(12, GPIO.OUT)
GPIO.output(12, GPIO.LOW)

pygame.init()
pygame.font.init()

FONT1 = pygame.font.SysFont("Arial", 24)

screen = pygame.display.set_mode([480, 320], pygame.FULLSCREEN)
pygame.display.set_caption("EXMATRIKULATOR")

running = True

while running:
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                        running = False

                if event.type == pygame.MOUSEBUTTONDOWN:
                        mouse = pygame.mouse.get_pos()
                        if 30 <= mouse[0] < 60 and 30 <= mouse[1] < 60:
                                GPIO.output(12, GPIO.LOW)
                        if 90 <= mouse[0] < 120 and 30 <= mouse[1] < 60:
                                GPIO.output(12, GPIO.HIGH)
                        if 450 <= mouse[0] < 480 and 0 <= mouse[1] < 30:
                                running = False

        screen.fill((255, 255, 255))

        pygame.draw.rect(screen, (255, 0, 0), (30, 30, 30, 30))
        pygame.draw.rect(screen, (0, 255, 0), (90, 30, 30, 30))
        pygame.draw.rect(screen, (255, 0, 0), (450, 0, 30, 30))
        screen.blit(FONT1.render("X", False, (0, 0, 0)), (458, 3))

        pygame.display.flip()

pygame.quit()

GPIO.cleanup()

It runs perfectly fine when started manually from the pi, but it doesn't autostart at bootup. I have tried many different ways, including all of these: https://www.dexterindustries.com/howto/run-a-program-on-your-raspberry-pi-at-startup/

So I'm starting to think I've got a big layer 8 Problem right here. What do I have to do, to autostart a python script with gui and gpio after a clean boot, so that it is visible?

I am using a 3.5" TFT touchscreen (with LCD-show from goodtft https://github.com/goodtft/LCD-show). Which stopped working after I added the autostart to the rc.local file, and worked again after removing it. Also, using rc.local I get prompted to login at boot, which doesn't appear without the addition of the line sudo python /home/pi/Desktop/pyscript.py I have also added alias python=python3 in ~/.bashrc because I will only use python3 on this raspberry and want to make sure that my scripts get executed with the correct version.


Solution

  • A good friend helped me. :D

    The solution is to put @/usr/bin/python3 /path/to/file.py into the autostart file at /etc/xdg/lxsession/LXDE-pi.

    The keyword I was missing was LXDE.

    https://www.raspberrypi-spy.co.uk/2014/05/how-to-autostart-apps-in-rasbian-lxde-desktop/