The Awesome RaspberryPI

From raspberypy.org: The Raspberry Pi is a credit-card sized computer that plugs into your TV and a keyboard. It is a capable little computer which can be used in electronics projects, and for many of the things that your desktop PC does, like spreadsheets, word-processing and games. It also plays high-definition video. We want to see it being used by kids all over the world to learn how computers work, how to manipulate the electronic world around them, and how to program.

This notebook is going to just focus on using the Raspbery Pi for electronics projects.

Blink!!

Well start with something simple, lets blink an LED. To do this, we're going to connect the Raspberry Pi's General Purpouse Input Output (GPIO) #18 up to an LED.

So, first we connect the RaspBerry Pi's GPIO18 pin to the long wire on the LED. GPIO18 is connected to pin 12 on the Raspberry PI (yes it is confusing but frequently the number the CPU uses to reference a GPIO pin is not the same as the pin number it is connected to).

Next we need to connect the short pin of the LED to a component called a resistor. The other end of the resistor connects to the ground pin (the ground acts like the negative side of a battery). A resistor as the name implies resists the flow of electricity. We need this resistor because the Raspberry PI GPIO pins operate at 3.3 volts but most LEDs can only handle 2 volts or so. This resistor is frequently called a current limiting resistor since that's what it's doing.

Now that it's all wired up, when we tell the Raspberry PI to turn on GPIO18 it will turn the switch on electricity will flow from the GPIO18 pin, into the long lead of the LED, out, through the current limiting resistor and finally to the ground.

Before we use a GPIO pin we have two do two things.

  1. Set the pin numbering we're using (the python module can use either the board pin numbers GPIO.BOARD or the logical GPIO pin numbers GPIO.BCM)
  2. Set the mode the port should be in, this can be Input if it's going to be getting values from the pin, Output if it's going to be setting the pin to specific values.

In [13]:
# Blink an LED on pin 18.
# Connect a low-ohm (like 360 ohm) resistor in series with the LED.

import RPi.GPIO as GPIO
import time

# A variable so we can change the PIN number for this script in once place
# if we move the LED to a different pin.
PIN = 18

# Set the pin to do output
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIN, GPIO.OUT)


# Loop forever blinking our led
while True:
    # Switch the pin off for half of a second
    GPIO.output(PIN, 0)
    time.sleep(.5)

    # Now turn it back on
    GPIO.output(PIN, 1)
    time.sleep(.5)


---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-13-08661e8511cb> in <module>()
     18     # Switch the pin off for half of a second
     19     GPIO.output(PIN, 0)
---> 20     time.sleep(.5)
     21 
     22     # Now turn it back on

KeyboardInterrupt: 

Oooh, bright lights

Although the computer is only able to turn the LED off or on, it is possible for it to rapidly cycle the LED to change the brightness. This is frequently called Pulse Width Modulation (PWM) and we hooked the LED to GPIO18 because that specific GPIO pin has a hardware PWM circuit which does a better job than cycling the LED in software.

The Raspberry PI GPIO module allows us to change how frequently the LED stays on by changing it's duty cycle. Below we show an LED going brigher and dimmer.


In [14]:
import time
import RPi.GPIO as GPIO

# Set our pin to output mode
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.OUT)

# Set the PWM frequency in Hz (cycles per second)
p = GPIO.PWM(12, 60)  # channel=12 frequency=60Hz

# Start doing PWM
p.start(0)

try:
    # Loop forever
    while True:
        # Increase the duty cycle (percentage of time the pin is on) from
        # 1% to 100%.  This will cause the LED to get brighter
        for dc in range(0, 101, 1):
            p.ChangeDutyCycle(dc)
            time.sleep(0.05)

        # Now decrease the duty cycle (time the pin is on) back to 1.  This will
        # cause the LED to dim
        for dc in range(100, -1, -1):
            p.ChangeDutyCycle(dc)
            time.sleep(0.05)
except KeyboardInterrupt:
    pass
p.stop()
GPIO.cleanup()

Interfacing with More than one thing


In [2]:
#!/usr/bin/python3

import RPi.GPIO as GPIO
import time
import sys
from range_finder import RangeFinder

# Set our pin to output mode
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.OUT)

# Set the PWM frequency in Hz (cycles per second)
p = GPIO.PWM(12, 60)  # channel=12 frequency=60Hz

# Start doing PWM
p.start(0)


if __name__ == '__main__':
    sensor = RangeFinder()

    print('Running main')
    while True:
        percent = sensor.average_distance_percent
        print(100-percent)
        if percent == 100:
            p.ChangeDutyCycle(1)
        elif percent < 100:
            p.ChangeDutyCycle(100-percent)

        time.sleep(.1)


Running main
93.2866157239
93.3810570661
93.500181941
93.3397389789
93.3671055042
93.3204214316
93.3070064682
93.4234483504
93.3375925847
93.311835855
93.3563735335
93.2952013004
93.3424219716
93.3429585701
93.3472513584
93.333836395
93.3375925847
93.3408121759
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-2-c38c42102f0e> in <module>()
     22     print('Running main')
     23     while True:
---> 24         percent = sensor.average_distance_percent
     25         print(100-percent)
     26         if percent == 100:

/home/pi/presentation/range_finder.py in average_distance_percent(self)
     90     @property
     91     def average_distance_percent(self):
---> 92         return self.average_distance(unit='percent')
     93 
     94     def average_distance(self, unit='inch'):

/home/pi/presentation/range_finder.py in average_distance(self, unit)
    106             else:
    107                 tot += self.distance_inch/12.0
--> 108             time.sleep(0.1)
    109         return tot / self.samples
    110 

KeyboardInterrupt: 


In [19]:
import RPi.GPIO as GPIO
import time

# A variable so we can change the PIN number for this script in once place
# if we move the LED to a different pin.
PIN = 7

# Set the pin to do output
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIN, GPIO.OUT)


# Loop forever blinking our led
while True:
    # Switch the pin off for half of a second
    GPIO.output(PIN, 0)
    time.sleep(5)

    # Now turn it back on
    GPIO.output(PIN, 1)
    time.sleep(5)

GPIO.cleanup()


---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-19-7c8cd00ee558> in <module>()
     18     # Switch the pin off for half of a second
     19     GPIO.output(PIN, 0)
---> 20     time.sleep(5)
     21 
     22     # Now turn it back on

KeyboardInterrupt: 

In [23]:
import RPi.GPIO as GPIO
import time

# A variable so we can change the PIN number for this script in once place
# if we move the LED to a different pin.
PIN = 7

# Set the pin to do output
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIN, GPIO.OUT)
GPIO.output(PIN, 1)

#GPIO.cleanup()

In [22]:


In [ ]: