IEEE Raspberry Pi Workshop


Introduction

Welcome to the IEEE Raspberry Pi workshop. Here's the first tasks before we can get going:

  1. Obtain your assigned pi with accessories
  2. Power on your pi with the provided power supply
  3. After about a minute, attempt to ssh into your pi
  4. Update repositories and download necessary packages

How to ssh into the pi

Each pi will be netreg'd to the appropriate person's account. You can find the hostname for the pi under registered devices at netreg.utk.edu

Username: pi
Password: raspberry
You can input this information into PuTTY or any other ssh client to remotely access the pi.

If you don't see a new device on your network registration. You can manually register it. I can provide you with the wifi MAC address for this

Updating and Installing Software

To update the repositories on your pi, simply run

sudo apt-get update
Once you have done that, you are ready to being installing software.

For this workshop, we need to install a few pieces of software. Run

sudo apt-get install vim python-setuptools libffi-dev libssl-dev
Once that is complete, then run
sudo easy_install pip
With pip, we will run
sudo pip install pyopenssl ndg-httpsclient pyasn1 twython
This installs the necessary packages for us to complete the planned exercises successfully.


Information about the Raspberry Pi 2

The Raspberry Pi 2 is the successor to the Raspberry Pi board released in 2012. The new model improves on its predecessor in various ways. Perhaps most importantly, the Raspberry Pi 2 features a newer, multi-core ARM processor.

Specs Overview


Task 1 - Controling an LED

The first step to controlling an LED is understanding what an LED is. An LED is a Light Emitting Diode. It operates like other diodes in that it ideally only allows current in one direction. The symbol below is the symbol used in circuit schematics to denote an LED.

However, in this workshop, we are using an RGB LED. The RGB LED we are using can be treated like three diodes which share a common cathode (or ground for our purposes).

Leg 1 -     red annode
Leg 2 - common cathode
Leg 3 -   green annode
Leg 4 -    blue annode
		

Now, we are ready to connect the LED to the pi. Be careful in this step because improper wiring can damage the LED or the pi. Using the schematic above, you should connect each annode in series with a resistor to a GPIO pin on the pi while taking note of the pin number. You should then connect the cathode to a ground pin on the pi with no series resistors.

Consult pinout.xyz to determine suitable pins.
Ask if you are unsure.

Once the LED is correctly wired to the pi, you are ready to program a script to control the LED. Today, we are going to use Python. Python is a common scripting language, and it is very popular especially in the pi community.

Write a script

Open up vim or nano from the terminal (if you don't know what vim is - use nano for now). Just like C, we need to include the appropraite libaries for our program.

import time
import RPi.GPIO as GPIO

We need the time library for controlling the duration the LED is activated, and we need the GPIO library to control the GPIO pins.

Next, we need to define the states of the LED and the pins on the pi which are connected to the LED. The LED will be enabled when we pass a logic "1" or high voltage to it, and the LED will be off when we pass a logic "0" to it. I connected the red annode to pin 16, the green annode to pin 18, and the blue annode to pin 22 when I did this. Replace those numbers with your own.

# Define enable and disable states
RGB_ENABLE = 1
RGB_DISABLE = 0

#LED CONFIG - Set GPIO Ports
RGB_RED = 16
RGB_GREEN = 18
RGB_BLUE = 22
RGB = [RGB_RED, RGB_GREEN, RGB_BLUE]

Now, that the LED pins and states are defined. We need to set up the GPIO pins for output. The GPIO library provides GPIO.setmode and GPIO.setup to accomplish this. GPIO.setup will determine the pin's mode, so we will use it to set the pin to output.

def led_setup():
    # Set up the wiring
    GPIO.setmode(GPIO.BOARD)

    # Setup GPIO ports
    for val in RGB:
        GPIO.setup(val, GPIO.OUT)

With everything now set up, we can define some functions to light up and turn off each color of the LED. With GPIO, this is simple because you just have to set the state of the pin to be either logic 1 or 0.

# lights up the LED
def led_activate( color ):
    GPIO.output( color, RGB_ENABLE )

# turns off the LED
def led_deactivate( color ):
    GPIO.output( color, RGB_DISABLE )

# turns off all of the colors of the LED
def led_clear():
    for val in RGB:
        GPIO.output(val, RGB_DISABLE)

Now you can play with the LED using these functions. One possible option to extend this code is to add a blink routine. Below is some example code showing a script that cycles through the difference colors for a couple seconds at a time.

led_setup()
led_clear()

# flash red
led_activate(RGB_RED)
time.sleep(2)
led_deactivate(RGB_RED)

# flash blue
led_activate(RGB_BLUE)
time.sleep(2)
led_deactivate(RGB_BLUE)

# flash green
led_activate(RGB_GREEN)
time.sleep(2)
led_deactivate(RGB_GREEN)

# all three at once
led_activate(RGB_RED)
led_activate(RGB_BLUE)
led_activate(RGB_GREEN)
time.sleep(2)
led_clear()

led_clear()
GPIO.cleanup()

Make sure to call GPIO.cleanup() at the end of every script in which you use the GPIO pins.


Task 2 - Twitter Bot

The next task is to dive into the Twython library which provides an easy way to make use Twitter's API to do various things.

Register a Twitter App

First, you must register a twitter app such that you may obtain an API code. Go to https://apps.twitter.com/app/new and register a new app. Name it whatever you want. The name and URL fields are not important. Once that is complete, we will need to grab the Consumer key and the Consumer Secret for our app.

Next, we will need to connect your app with your twitter account. Click the create my access token button and take note of the Access token and the Access token secret. These will also be required for our app.

import sys
from twython import Twython
CONSUMER_KEY = '***************YOUR DATA*****************'
CONSUMER_SECRET = '***************YOUR DATA*****************'
ACCESS_KEY = '***************YOUR DATA*****************'
ACCESS_SECRET = '***************YOUR DATA*****************'

api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET)

Use the above code to set up a connection with Twitter. Fill in the appropriate fields we determined earlier.

To post a status update, it is now very easy! Just call api.update_status("status here"). For example, if you want to make your script post a passed command line argument as your new status, use the below code.

api.update_status(status=sys.argv[1])

Connect Twitter Hashtags to the LED

Now, to bring everything together, we can use the Twitter API in conjunction with the attached LED. This next script will track a specified hashtag on Twitter. When a tweet is posted with that hashtag, a tweet is printed to standard output (the terminal), and the LED is flashed.

Just as before, we must import the required libraries. This time, we will be using the libraries both for Twython and the GPIO ports.

import time
import RPi.GPIO as GPIO
from twython import TwythonStreamer

We also need to copy the LED definitions and functions from earlier. Remember to replace my pin numbers with yours if you used different GPIO pins.

# Define enable and disable states
RGB_ENABLE = 1
RGB_DISABLE = 0

# LED GPIO ports
RGB_RED = 16
RGB_GREEN = 18
RGB_BLUE = 22
RGB = [RGB_RED, RGB_GREEN, RGB_BLUE]

# setup GPIO
def led_setup():
    # Set up the wiring
    GPIO.setmode(GPIO.BOARD)

    # Setup GPIO ports
    for val in RGB:
        GPIO.setup(val, GPIO.OUT)

# lights up the LED
def led_activate( color ):
    GPIO.output( color, RGB_ENABLE )

# turns off the LED
def led_deactivate( color ):
    GPIO.output( color, RGB_DISABLE )

# turns off all of the colors of the LED
def led_clear():
    for val in RGB:
        GPIO.output(val, RGB_DISABLE)

You also need the Twitter API key information again.

# Twitter application authentication
CONSUMER_KEY = '***************YOUR DATA*****************'
CONSUMER_SECRET = '***************YOUR DATA*****************'
ACCESS_KEY = '***************YOUR DATA*****************'
ACCESS_SECRET = '***************YOUR DATA*****************'

Now we need to make a class which will set up callbacks from the Twython Streamer class. This function will be executed by the Twython library when the specified hashtag is found.

# Setup callbacks from Twython Streamer
class MyStreamer(TwythonStreamer):
    def on_success(self, data):
        if 'text' in data:
            # Print the tweet
            print data['text'].encode('utf-8')
            print

            # flash the red LED when a tweet is found
            led_activate(RGB_RED)
            time.sleep(0.5)
            led_deactivate(RGB_RED)

Now, the rest of the script is simple. We need to run the led_setup() function, and we need to instantiate an object of the class we created above. Then, we just need to pass a hashtag we want to the object, and we an sit back and watch it work.

# Call the LED setup function
led_setup()

# set our desired hashtag
TERMS = '#TheWalkingDead'

# create an object and let it run
try:
    stream = MyStreamer(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, ACCESS_SECRET)
    stream.statuses.filter(track = TERMS)
except KeyboardInterrupt:
    # if we recieve a keyboard interrupt - clean up the GPIO so the app exits nicely
    GPIO.cleanup()

Note: you will probably have to run the script as superuser (so use `sudo python (script)`).


Additional Information

Code repository for the workshop: https://github.com/jptech/rpi_workshop


Sources

The following websites were used in the creation of this workshop: