Tuesday, 4 June 2013

Things I wish I knew about python and the WebIDE right away...

Python is interpreted, so you need to feed your source code to the interpreter program, typically with a command like python MyProgram.py. or you can just run python then start typing in commands the same as they would appear in your code. It takes me back to the bad old days of MS/BASIC. Alternately, if the first line in the .py file is #!/usr/bin/env python and you have changed the mode of the .py file to allow execution (chmod +x MyProgram.py) then you can run the file directly by name.

Indentation defines extent the way {} do in C, so whitespace matters.

The first thing you need to do is import the libraries you want to use in your code:

import sys
import RPi.GPIO as GPIO

imports the whole sys library, imports the RPi.GPIO library but lets you refer to it as GPIO for function calls like GPIO.setup(RST, GPIO.OUT)

from time import sleep

just imports the sleep function from the time library. Python finds all of these somewhere in the system libraries by following the path. You can add to the path like this:

sys.path.append("/home/pi/Examples")

so that

import Nokia.RWSpypcd8544 as nokia

will find the code in /home/pi/Examples/Nokia/RWSpypcd8544.py as long as /home/pi/Examples/Nokia/__init__.py also exists, even if it is empty. The code in the init file will run before importing the code from the named file. Note the use of a period rather than a slash. Now you can call things from RWSpypcd8544 with function calls like nokia.showFlower().

Running a WebIDE python program on system boot


It's pretty straightforward to use the WebIDE to write and run python programs from a web connection. Once those programs are working, you might want to run one of them automatically when the Pi starts up. /etc/rc.local is a script that will run as the final part of the boot sequence, so you can add a command to this script. The command I added was

sudo /usr/share/adafruit/webide/repositories/my-pi-projects/BlinkButtons/flashyNokia.py &

to run the program in background. Running it with sudo is required to give full access to the hardware features. To make the script run you will need to

sudo chmod +x /etc/rc.local

in order to make rc.local executable. You'll also have to run chmod +x against the .py file created by the IDE. You only need to do all of this once, even when you modify the program in the IDE.

No comments:

Post a Comment