Raspberry Pi Device Engineering 2019

Wray Mills, 2019-07-22, Classes

device, raspberry pi

Description

Camp Session July 22 - 25, 9 - 12pm

Campers create a cool technology project using a mini computing device (Raspberry Pi), coding skills and of course, their imaginations.

Materials fee to take home the project.

Instructors

Lead Instructor

Chris

Additional Interns/Instructors

Learning Objectives

Materials

Class

On the line Resources

On the line Presentations

Repos

Day 1

Setup

Plan

Students will set up their Raspberry Pis with the Initial Config instructions below. Instructors will go over the hardware and software of the Raspberry Pi. After students have set up their Raspberry Pi, they will look at the Python code behind the various games on the Raspberry Pi. Instructors will challenge students to find a way to make various games harder or easier to win by changing various elements of the code.

Initial Config

For classes and camps, we always start with an SD card that has raspian (the Operating System) pre-installed. Of course, for the last camp, we started with blank SD cards! So, on that first day, we were actually loading the OS on your cards.

After logging in, we then ran

sudo raspi-config

in order to extend the filesystem, set the correct time, and set the correct keyboard.

We also configured your wi-fi adapter by running the gui

startx

and using the wifi settings to scan for networks, choose the network, type in the password, and connect. Remember, you'll have to do this for your home wireless netework. Try to run startx without sudo. If the GUI doesn't come up, you may have to use sudo. When you are using the LEDS or the temp sensor, you will have to run python as sudo.

Config for LEDs, Minecraft and Temp sensor

In lieu of burning a pre-configured SD, we can run this script on a raspbian pi (model 2 with pre-loaded raspian from Adafruit) in order to get python development tools, the RPi GPIO library and the DHT library from Adafruit. Note, that this setup assumes your pi has network (Internet) connectivity. You can type in these commands separately, starting with the first line not containing a #.

#!/bin/sh
# Run this command using sudo

# Beforehand, you should expand filesystem, turn on ssh
# and of course configure network.

sudo apt-get update
sudo apt-get install python-dev
sudo apt-get install python-pip
sudo easy_install -U distribute
sudo pip install --upgrade RPi.GPIO
sudo apt-get install build-essential
git clone git://github.com/adafruit/Adafruit_Python_DHT
cd Adafruit_Python_DHT
sudo python setup.py install
cd ..

Actual

We had a good morning learning about the Raspberry Pi's and getting them all set up. We started with learning about all the different components on a Raspberry Pi and how to identify them. Next, we learned how to burn an SD card with the correct operating system and what the basic setup involves. The rest of the class was spent exploring the different software contained on the Pi and typing up some Python code to start playing around with the LEDs.

Day 2

Setup

Plan

Students will practice setting up their Raspberry Pis on their own. Instructors will introduce the students to breadboards, and students will work on a program to light up LEDs on their breadboard. Instructors will also go how to read input from a user, and students will work on a Morse Code program.

LEDs

So, for the Output portion of the I/O lesson (easier than input so you may as well start here), assume a green LED is wired to #20 and a red LED is wired to #21.

import RPi.GPIO as GPIO

DEBUG = 1

GPIO.setmode(GPIO.BCM)
GREEN_LED = 20 
RED_LED = 21
GPIO.setup(GREEN_LED, GPIO.OUT)
GPIO.setup(RED_LED, GPIO.OUT)


def green_led(state):
    GPIO.output(GREEN_LED,state)

def red_led(state):
    GPIO.output(RED_LED,state)

So, a simple session to use these methods would look like this:

sudo python
>>>from led import *
>>>green_led(1)
>>>red_led(1)
>>>green_led(0)
>>>red_led(0)
>>>quit()

Extend the LED Morse Code output

We started a program that reads input from a user and converts that input into LED morse code. Start with this snippet and see if you can finish it -- let us know how you do!!

# Remember, everything after a # is a comment
# Comments are here for humans to explain code to
# other humans. Anything after a # is ignored by
# the computer

# Use the imports you have for the leds
# For example: from led import *


def dash():
    #whatever code you already have here
    print("-"),

def dot():
    # whatever code you already have here
    print("."),

def morse_a():
    dot()
    dash()

def morse_b():
    dash()
    dot()
    dot()
    dot()

def morse_c():
    dash()
    dot()
    dash()
    dot()

def morse_d():
    dash()
    dot()
    dot()

def morse_e():
    dot()

def morse_t():
    dash()

def morse(character):
    try:
        if character != " ":
            globals()["morse_"+character.lower()]()
    except KeyError:
        print(character + " not defined in morse yet."),


for i in range(10):
    print("Type in text to convert to morse code.")
    text = raw_input()
    for character in text:
        morse(character)
        print(" ")

If you save this file as "morse_output.py" for example, you may run it with:

sudo python morse_output.py

Actual

To start the morning, we continued programming our Raspberry Pis and having fun with the LEDs. We reviewed the components on the Pi and looked over our breadboards. Then, we reviewed our Python code from the day before and started working on the Morse Code activity. We finished the morning talking about software for the Raspberry Pi, including how to install new software and keep everything updated.

Day 3

Setup

Plan

Students will set up their Raspberry Pis and breadboards. Instructors will help students set up a temp/humidity sensor program. Students will also learn how to setup Minecraft on their Raspberry Pis!

Input Sensor (Temp/Humidity Sensor including in your Tech Em kit)

For the Input part of the lesson, here is some code that provides a single simple method to return temperature and humidity (from a DHT-22 temperature/humidity sensor wired to pin #4).

#
# Template code for temperature and humidity from an Adafruit DHT22
# sensor. Don't forget to update this file if you connect the DHT22 
# to another data pin,
# want to change the delay, or logic for mailing. 
# For example, you may only want to
# send notifications when certain thresholds are exceeded.
# 
# Code provided for Tech Em students and open under Gnu GPL
#
# Wray Mills
# 20141115
#

import os
import time
import Adafruit_DHT
# Tech Em mail utility
# from mailit import *

sensor = Adafruit_DHT.DHT22
pin = 4 

def read_temp_humidity():
    humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
    temp_f = temperature * 9.0 / 5.0 + 32.0
    return temperature, temp_f, humidity

Minecraft Setup

Launch python with sudo, import this file and call the method to get the tuple of celsius temperature, fahrenheit temperature, and relative humidity.

Let's grab some Python libraries that can connect to your Minecraft World. Login to your pi and launch the GUI:

startx

Open up a browser and go to:

www.wiley.com/go/adventuresinminecraft

and download the starter kit. Choose "open" and open the program called Xarchiver. Click Action -> Extract on the Xarchiver menu. Type /home/pi in the Extract to: text box.

Now, open up IDLE (Python) and create a new program file. You'll want to save this file in the "My Adventures" folder you just created. You can name this first file "hello_minecraft.py". This actually assumes you have already done the LED input lesson and have a file led.py that you have copied into your "My Adventures" folder. Finally, since this code uses the raspberry pi I/O, you'll need to open up a new terminal window (LX Terminal), change directory (using "cd") to "My Adventures" and run the file with sudo.

import mcpi.minecraft as minecraft

mc = minecraft.Minecraft.create()

mc.postToChat("Hello Minecraft World")

import time

while(1):
    pos = mc.player.getTilePos()

    print(pos.x)
    print(pos.y)
    print(pos.z)

    from led import *

    if pos.y > 5:
        green_led(1)
    else:
        green_led(0)

    time.sleep(5)

So, running this would go something like this:

cd "My Adventures"
sudo python hello_minecraft.py

Want to build something?

import mcpi.minecraft as minecraft
mc = minecraft.Minecraft.create()

import mcpi.block as block

pos = mc.player.getTilePos()

for y in range(150):
    mc.setBlock(pos.x+2,pos.y+y,pos.z,block.TNT.id)

Here is another cool program to try.

import mcpi.minecraft as minecraft
import mcpi.block as block
import time

mc = minecraft.Minecraft.create()

bridge = []

def buildBridge():
    pos = mc.player.getTilePos()
    b = mc.getBlock(pos.x,pos.y-1,pos.z)
    if b == block.AIR.id or b == block.WATER_FLOWING.id or b == block.WATER_STATIONARY.id:
        mc.setBlock(pos.x,pos.y-1,pos.z,block.GLASS.id)
        coordinate = [pos.x,pos.y-1,pos.z]
        bridge.append(coordinate)

    elif b != block.GLASS.id:
        if len(bridge) > 0:
            coordinate = bridge.pop()
            mc.setBlock(coordinate[0],coordinate[1],coordinate[2],block.AIR.id)
            time.sleep(0.25)

while True:
    time.sleep(0.25)
    buildBridge()

And while you are at it, can you post the current temp to the chat?? The hint here is that you should copy your temp.py file into your "MyAdventures" sub-directory, comment-out the deliver method and update the print method (at the end of the file) to postToChat. And, don't forget to do the minecraft setup (imports and creation) in order to postToChat.

What else can you do? Do you want to do? You all now have temp input, led output, minecraft control, and outbound email capabilities!!

Actual

We finished anything we didn't get accomplished from the previous day and reviewed our Python code. The students spent the first part of the morning playing around and learning about how Python code could control things we plugged into our breadboard. The temperature and humidity sensor was introduced along with some basic Python code to make it work. We then worked on creating a Python program that would loop forever, printing out the time, date, temp, humidity reading every 5 seconds and all compared results! Finally, we came up with creative ways to use LEDs and the sensor to make things more colorful! The rest of class we spent with Minecraft, and we looked at different ways that our Python code could make weird and mysterious things happen within our Minecraft worlds.

Day 4

Setup

Plan

Students will work on adding more elements to their programs from the week. They will also work on a program to log the data from the temp/humidity sensor. Instructors will review with students how to setup their Raspberry Pis at home.

Google Spreadsheet DHT Sensor Data-logging

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#!/usr/bin/python

# Google Spreadsheet DHT Sensor Data-logging Example

# Depends on the 'gspread' package being installed.  If you have pip installed
# execute:
#   sudo pip install gspread

# Copyright (c) 2014 Adafruit Industries
# Author: Tony DiCola

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import sys
import time
import datetime

import Adafruit_DHT
import gspread

# Type of sensor, can be Adafruit_DHT.DHT11, Adafruit_DHT.DHT22, or Adafruit_DHT.AM2302.
DHT_TYPE = Adafruit_DHT.DHT22

# Example of sensor connected to Raspberry Pi pin 23
DHT_PIN  = 12 
# Example of sensor connected to Beaglebone Black pin P8_11
#DHT_PIN  = 'P8_11'

# Google Docs account email, password, and spreadsheet name.
GDOCS_EMAIL            = 'XXX'
GDOCS_PASSWORD         = 'XXX'
GDOCS_SPREADSHEET_NAME = 'XXX'

# How long to wait (in seconds) between measurements.
FREQUENCY_SECONDS      = 30


def login_open_sheet(email, password, spreadsheet):
    """Connect to Google Docs spreadsheet and return the first worksheet."""
    try:
        gc = gspread.login(email, password)
        worksheet = gc.open(spreadsheet).sheet1
        return worksheet
    except:
        print 'Unable to login and get spreadsheet.  Check email, password, spreadsheet name.'
        sys.exit(1)


print 'Logging sensor measurements to {0}.'.format(GDOCS_SPREADSHEET_NAME)
#print 'Press Ctrl-C to quit.'
worksheet = None

# Login if necessary.
if worksheet is None:
    worksheet = login_open_sheet(GDOCS_EMAIL, GDOCS_PASSWORD, GDOCS_SPREADSHEET_NAME)

# Attempt to get sensor reading.
humidity, temp = Adafruit_DHT.read(DHT_TYPE, DHT_PIN)

# Skip to the next reading if a valid measurement couldn't be taken.
# This might happen if the CPU is under a lot of load and the sensor
# can't be reliably read (timing is critical to read the sensor).
if humidity is None or temp is None:
    time.sleep(2)

print 'Temperature: {0:0.1f} C'.format(temp)

print 'Humidity:    {0:0.1f} %'.format(humidity)

# Append the data in the spreadsheet, including a timestamp
try:
    worksheet.append_row((datetime.datetime.now(), temp, temp*9.0/5.0 + 32.0,humidity))
except:
    # Error appending data, most likely because credentials are stale.
    # Null out the worksheet so a login is performed at the top of the loop.
    print 'Append error, logging in again'
    worksheet = None
    #time.sleep(FREQUENCY_SECONDS)
    #continue

# Wait 30 seconds before continuing
print 'Wrote a row to {0}'.format(GDOCS_SPREADSHEET_NAME)
#time.sleep(FREQUENCY_SECONDS)

Actual

We had a lot of fun the last day of camp! The kids worked on finishing up any of the activites that they were working on the day before, and continued experimenting with their breadboards. I think we have definitely mastered turning LEDs on and off, and it's been a lot of fun seeing what they come up with.

Day 5- Project Friday!

Setup

Plan

Students will continue to work on an activity of their choosing from the week. This is a more open ended day and will be guided by the interests of the students. One program that students can work on is a program that will email the tempature readings from the sensor to the user.

Email Temapture Sensor Program

After wiring your DS18B20, you need to prep your pi for using it. After logging in, do this:

sudo nano /boot/config.txt

And add this line to it:

dtoverlay=w1-gpio

Now, reboot your pi:

sudo reboot

Now, let's test the temp sensor with these commands:

sudo modprobe w1-gpio
sudo modprobe w1-therm
cd /sys/bus/w1/devices
ls
cd 28<tab>
cat w1_slave

You should see two lines with a "YES" at the end of the first line and the temp reading at the end of the second. Once you've done this, go ahead and

cd ~
sudo startx

and launch python2, create a new file and put the code below in it. Save it as temp.py.

Here is the associated code that reads from the DS18B20 temp sensor.

import os
import glob
import time
#from mailit import *

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'

def read_temp_raw():
    f = open(device_file, 'r')
    lines = f.readlines()
    f.close()
    return lines

def read_temp():
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = float(temp_string) / 1000.0
        temp_f = temp_c * 9.0 / 5.0 + 32.0
        return temp_c, temp_f

while True:
    print('The current temp is: %dC, %dF' % (read_temp()))
    #deliver('The current temp is: %dC, %dF' % (read_temp()))
    time.sleep(1500)

This is a very simple/generic mailing routine. Uncomment the "from mailit import *" and the function call to "deliver" in the above routine to have your temp reading sent via email. You should save this code in a file called mailit.py.

# Simple smtp mail utility to be used by Tech Em students.
# This will run on the RPi with the Occidentalis install.
# Thus, it is a handy utility to use along with adafruit sensors
#
# 201406 Wray Mills
#

import subprocess
import smtplib
import socket

from email.mime.text import MIMEText
import datetime

### 
# Change to your settings
###
pi_name = 'wray-pi'
to = 'somebody@somewhere.com'

## Feel free to reuse the techem student relay
mail_user = 'student@techemstudios.com'
mail_password = 'pword-on-whiteboard'

def deliver ( message, subject = 'RPi output' ):
    smtpserver = smtplib.SMTP('smtpout.secureserver.net', 3535) # Use 587 for gmail
    smtpserver.ehlo()
    #smtpserver.starttls() # Uncomment this line for gmail
    smtpserver.login(mail_user, mail_password)
    msg = MIMEText(message)
    msg['Subject'] = subject
    msg['From'] = '(%s)%s' % (pi_name,mail_user)
    msg['To'] = to
    smtpserver.sendmail(mail_user, [to], msg.as_string())
    smtpserver.quit()

Actual

Today was our project day and as we had been working on some mini projects throughout the week with our breadboards, some of the kids continued working on those and making some last minute changes. We also talked about different things you could do with your Raspberry Pi like make it into a media center or a retro gaming box!