If you code in Python, the RPi.GPIO Python library (included with Raspbian) lets you configure, read, and write to GPIO pins.

We’ve created a Python script that shows how to read and write with the RPi.GPIO library.

  • If you’re using a browser, click here for the script.

  • To download the script to the current directory using a terminal, enter wget http://developer.opto22.com/downloads/PythonScript.py

The comments in the script point out where it:

  • Invokes the Python interpreter
  • Includes the RPi.GPIO library and sets GPIO as a local name in the script
  • Sets the pin-numbering scheme for the script
    (The GPIO.BOARD option means that that you’re referring to the pins by their physical pin number. To refer to the pins by their GPIO pin number, use the GPIO.BCM option.)
  • Configures physical pin number 13 as input.
    Note: Physical pin 13 is mapped to rack position 10.
  • Reads the input point mapped to pin 13 and stores it in a variable.
  • Prints the point’s value to the terminal.
  • Configures physical pin number 15 as output.
    Note: Physical pin 15 is mapped to rack position 11.
  • Turns On the output point mapped to pin 15.
  • Turns Off the output point mapped to pin 15.
The script assumes you have a 16-module rack, an input module in rack position 10, and an output module in position 11. The script uses physical pin numbers and not GPIO pin numbers or I/O module rack positions, but you can edit the script to use GPIO pin numbers.

To run the script:

  1. If necessary, modify the pin numbers in the script to correspond to I/O modules on your rack.
  2. Make the script executable by entering chmod 755 PythonScript.py
  3. Run the script by entering ./PythonScript.py

The output looks something like this:

running the Python script

Back to Examples for Raspberry Pi