Friday 29 January 2016

Trying hard, eventually got R_PI to do something

So I thought, let's try a simple Python program on the R_PI. I know, build some traffic lights. I found a solution on the web, but getting it going was another matter.

1. I ran the desktop environment over VNC to my iMac, this means connecting by "ssh", running the server R_PI "vncserver :0" then starting the VNC Viewer program on my iMac pointing to "raspberrypi.local" and entering the password. (I had already installed the R_PI app "tightvncserver" to enable this... and the bonjour system to avoid the need to enter IP addresses)

2. On the desktop environment I opened Programming > Python3 and File >New

3. I typed in the code for the program:

#pin definitions
GPIO_SWITCH = 17
GPIO_RED = 22
GPIO_AMBER = 23
GPIO_GREEN = 24

# timings
TIME_CHANGE = 1
TIME_RED = 5
TIME_GREEN = 5

# libraries
import RPi.GPIO as GPIO
import time

# system settings
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

# pin setups
GPIO.setup(GPIO_RED, GPIO.OUT)
GPIO.setup(GPIO_AMBER, GPIO.OUT)
GPIO.setup(GPIO_GREEN, GPIO.OUT)
GPIO.setup(GPIO_SWITCH, GPIO.IN, pull_up_down=GPIO.PUD_UP)

# initial state
GPIO.output(GPIO_RED, True)
GPIO.output(GPIO_AMBER, False)
GPIO.output(GPIO_GREEN, False)

# loop
while 1:
        time.sleep(TIME_RED)

        GPIO.output(GPIO_AMBER, True)

        time.sleep(TIME_CHANGE)

        GPIO.output(GPIO_RED, False)
        GPIO.output(GPIO_AMBER, False)
        GPIO.output(GPIO_GREEN, True)

        while GPIO.input(GPIO_SWITCH):
                time.sleep(0.25)

        GPIO.output(GPIO_AMBER, True)
        GPIO.output(GPIO_GREEN, False)

        time.sleep(TIME_CHANGE)

        GPIO.output(GPIO_RED, True)
        GPIO.output(GPIO_AMBER, False)
and saved it as "traffic.py" in my "PGM" folder.

4. I then chose Run from the Python menu, PROBLEM! The GPIO stuff can only access the board pins if run as super user. So you can't run the program from the desktop python environment!!! How stupid can you get??? Or maybe no one has explained this to me yet... the documentation for the R_PI is a disaster...

5. So I closed the desktop python3 environment and connected to the R_PI from my Terminal program on the iMac and changed to the folder where I keep my programs "PGM", the program is called "traffic.py".
ssh pi@raspberrypi.local
pi@raspberrypi ~  $
pi@raspberrypi ~  $ cd PGM
pi@raspberrypi ~/PGM  $
Now I ran the program with
pi@raspberrypi ~/PGM  $ sudo python3 traffic.py
and off we go. it works. It also works fine if I start it the same way from a terminal window on the R_PI desktop (using LXTerminal).

6 BUT WHAT STUPIDITY that you cannot run the RPi.GPIO program from the desktop Python3 IDE!!!

No comments: