‹ COSMOS Cluster 9 · Maurício de Oliveira

Embedded Electronics with Raspberry Pi

Introduction to Raspberry Pi

Hardware Interfacing

GPIO with Python

Information on the header pins from http://pi4j.com:

http://pi4j.com/images/j8header-b-plus.png

The following Python 3 code imports the wiring library and sets up the pin mode to use the pin# shown in the figure above:

   import wiringpi as wiring
   wiring.wiringPiSetup()

Every pin has to be initialized before you can write to or read from it. There are 3 possibilities for initializing a pin:

Examples are:

   wiring.pinMode(6, 0) # sets WP pin 6 to input    (0) 
   wiring.pinMode(5, 1) # sets WP pin 5 to output   (1)
   wiring.pinMode(1, 2) # sets WP pin 1 to PWM mode (2)

Reading from and writing to a pin

You can now read from the input pin 6 with:

   wiring.digitalRead(6)

or write to the output pin 5 with:

   wiring.digitalWrite(5, 1) # to set a high voltage level (3.3V, ON)
   wiring.digitalWrite(5, 0) # to set a low voltage level (0V, OFF)

Using pull up or down resistors

If an input pin is connected to a circuit which might not have a well defined voltage at all times, e.g. a switch, it is possible to add resistors to the pin that will set a sort of "default" value for the pin at times when the input voltage is floating. Possible values are:

For example:

   wiring.pullUpDnControl(6, 1) # set pull-down  

will add a pull-down resistor to input pin 6.

Cleaning up

It is good practice to return the state of the ouput pins you used to OFF after running your code. A simple way to do that is with the *try-finally* Python construct. For example:

   wiring.pinMode(5, 1)          # sets pin 6 as output  
   wiring.pinMode(6, 0)          # sets pin 6 as input  
   wiring.pullUpDnControl(6, 1)  # set pull-down   
 
   try:
   
       # DO SOMETHING WITH PINS 5 AND 6
   
   finally:
   
       # CLEAN UP
       
       wiring.digitalWrite(5, 0) # sets pin 5 to 0 (0V, off)  
       wiring.pinMode(5, 0)      # sets pin 5 back as input

PWM on pin 1

Pin 1 can also be used as a hardware PWM output. In order to use this feature write:

   wiring.pinMode(1, 2)  # hardware pwm only works on pin 1
   wiring.pwmWrite(1, 512) # duty cycle 0 = OFF, 1024 = ON

Recovered from the original course wiki (server backup, August 2024).