Days 12-14: Raspberry Pi...

21
FCPS Ethan Seide Zane Alpher Introduction to Raspberry Pi

Transcript of Days 12-14: Raspberry Pi...

Page 1: Days 12-14: Raspberry Pi Project.docxfaculty.cse.tamu.edu/.../Rasberry-PIs/Days12-14RaspberryPiProject…  · Web viewThat’s because the names of the pins is not the name of the

FCPSEthan SeideZane Alpher

Introduction to Raspberry Pi

Turn on LEDCode (Python):#Ethan and Zane#8/5/14

#Importsimport RPi.GPIO as GPIO #For using raspberry pi I/O pinsimport time #For sleep command

#setup pin 7 on board as output pinGPIO.setmode(GPIO.BOARD)GPIO.setup(7, GPIO.OUT)

print('Turning on LED') #print to consoleGPIO.output(7, GPIO.HIGH) #set pin 7 HIGH

Page 2: Days 12-14: Raspberry Pi Project.docxfaculty.cse.tamu.edu/.../Rasberry-PIs/Days12-14RaspberryPiProject…  · Web viewThat’s because the names of the pins is not the name of the

print('Waiting 3 seconds')time.sleep(3) #wait 3 seconds

print('Turning off LED')GPIO.output(7, GPIO.LOW) #set pin 7 LOW

GPIO.cleanup() #resets pins to default values

NOTE: Even though it says that the LED is connected to pin 4, in reality you call on it as connected to pin 7. That’s because the names of the pins is not the name of the pin number. The pins actually are numbered 1-26, starting in the top left. All the odd numbers are on the left side, and all the even numbers are on the right side. Therefore, when you program the raspberry pi to turn on the LED, you tell it that it should turn on GPIO pin 7, not 4.

To run the above code, go to the terminal window and type in:sudo python filename

Since we saved ours in the projects folder on the desktop, we typed in:sudo python Desktop/projects/basicLED.py

Page 3: Days 12-14: Raspberry Pi Project.docxfaculty.cse.tamu.edu/.../Rasberry-PIs/Days12-14RaspberryPiProject…  · Web viewThat’s because the names of the pins is not the name of the

Basic InputCode (Python):#Ethan and Zane#8/6/14#basic button

#Importsimport RPi.GPIO as GPIO #for using raspberry pi IO pinsimport time

#setup pin 7 as an input pinGPIO.setmode(GPIO.BOARD)GPIO.setup(7, GPIO.IN)

#sets the last press of the buttonlastPress = 0;

#Loop that continuously runswhile True: #Updates readIn readIn = GPIO.input(7) #If the button is pressed, print to console #lastPress prevents the code from contiuously printing (debounce) if (readIn and lastPress == 0): print('Button Pressed!') lastPress = 1 #When the button is first turned on, the signal jumps up and down #The time.sleep() waits until after the swich so that it #doesn't double print time.sleep(0.1) #Resets lastPress when we stop pressing the button elif (not readIn and lastPress == 1):

Page 4: Days 12-14: Raspberry Pi Project.docxfaculty.cse.tamu.edu/.../Rasberry-PIs/Days12-14RaspberryPiProject…  · Web viewThat’s because the names of the pins is not the name of the

lastPress = 0

Note: Because the program is in a continuous loop, to end the program you need to type ctrl + c into terminal to break out of the program.

Page 5: Days 12-14: Raspberry Pi Project.docxfaculty.cse.tamu.edu/.../Rasberry-PIs/Days12-14RaspberryPiProject…  · Web viewThat’s because the names of the pins is not the name of the

Basic DC motorCode (Python):#Ethan and Zane#8/6/14#basic DC motor

import RPi.GPIO as GPIOimport time

#Setup pinsGPIO.setmode(GPIO.BOARD)GPIO.setup(16, GPIO.OUT) #Motor1 AGPIO.setup(18, GPIO.OUT) #Motor1 BGPIO.setup(22, GPIO.OUT) #Motor Enable

print("Turn motor on!")GPIO.output(16, GPIO.HIGH)GPIO.output(18, GPIO.LOW)GPIO.output(22, GPIO.HIGH)

#Waits 3 secondstime.sleep(3)

print("Reverse direction!")GPIO.output(16, GPIO.LOW)GPIO.output(18, GPIO.HIGH)GPIO.output(22, GPIO.HIGH)

time.sleep(3)

#Turns motor offGPIO.output(22, GPIO.LOW)

#Reset default valuesGPIO.cleanup()

Page 6: Days 12-14: Raspberry Pi Project.docxfaculty.cse.tamu.edu/.../Rasberry-PIs/Days12-14RaspberryPiProject…  · Web viewThat’s because the names of the pins is not the name of the

Diagram from http://computers.tutsplus.com/tutorials/controlling-dc-motors-using-python-with-a-raspberry-pi--cms-20051

Page 7: Days 12-14: Raspberry Pi Project.docxfaculty.cse.tamu.edu/.../Rasberry-PIs/Days12-14RaspberryPiProject…  · Web viewThat’s because the names of the pins is not the name of the

Basic PWM MotorCode (Python):#Ethan and Zane#8/6/14#PWM basic

import RPi.GPIO as GPIOimport time

#Setup pinsGPIO.setmode(GPIO.BOARD)GPIO.setup(16, GPIO.OUT) #Motor1 AGPIO.setup(18, GPIO.OUT) #Motor1 BGPIO.setup(22, GPIO.OUT) #Motor Enable

#Sets the enable pin as a pwm with a frequency of 100 Hzmotor1 = GPIO.PWM(22, 100)#The duty cycle equals 0motor1.start(0)

#Duty cycle is set at 0dc = 0

#Makes direction forwardGPIO.output(16, GPIO.HIGH)GPIO.output(18, GPIO.LOW)

#Enter in duty cycle (0-100) to change speed (0%-100%)while True: #Look at that validation! dc = int(input("Enter duty cycle: ")) #user inputs duty cycle motor1.ChangeDutyCycle(dc) #change duty cycle of motor

#Reset default valuesmotor1.stop()GPIO.cleanup()

Page 8: Days 12-14: Raspberry Pi Project.docxfaculty.cse.tamu.edu/.../Rasberry-PIs/Days12-14RaspberryPiProject…  · Web viewThat’s because the names of the pins is not the name of the

Note: Same circuit as basic motor project.Some useful commands (https://www.youtube.com/watch?v=uUn0KWwwkq8&feature=youtu.be&annotation_id=annotation_798006953&feature=iv&src_vid=W7cV9_W12sM):

Page 9: Days 12-14: Raspberry Pi Project.docxfaculty.cse.tamu.edu/.../Rasberry-PIs/Days12-14RaspberryPiProject…  · Web viewThat’s because the names of the pins is not the name of the

Basic API RequestCode (Python):#Ethan and Zane#8/6/14#Basic API

#Importsimport requests #Internet requests

#Need a key from weather underground to use APIkey = '<Your Key Here>'

#The url that we are looking at. Conditions in Saratoga SpringsapiUrl = 'http://api.wunderground.com/api/' + key +'/conditions/q/NY/Saratoga_Springs.json'

r = requests.get(apiUrl) #Gets data at the url

#The file type is a .json.#This converts the file into something that the program can useforecast = r.json

#Prints out the current temp (Fahrenheit) right now in Saratoga Springsprint forecast['current_observation']['temp_f']

Note: You need to download the requests library. To do that open terminal and type: sudo apt-get install python-requestsTo use the library in a program write import request at the beginning of the program. Every API on every website is different. Because you (the programmer) know what it will look like, you can write your program to use that specific API. Also, to use Weather Underground's API, you need to get a key from them. To do this, just go to their site and sign up. With the free package, you get limited on your requests per minute and per day. In the last line of the code above, you see that we are only printing the data under “current_observation” and then “temp_f”, which you can see is 69.6. If we wanted to reuse this code with a different type of request (even one on weather underground) we would have to look at what that page sends back and rewrite the program accordingly. (Getting Started with Raspberry Pi - O'reilly and Make)

Page 10: Days 12-14: Raspberry Pi Project.docxfaculty.cse.tamu.edu/.../Rasberry-PIs/Days12-14RaspberryPiProject…  · Web viewThat’s because the names of the pins is not the name of the
Page 11: Days 12-14: Raspberry Pi Project.docxfaculty.cse.tamu.edu/.../Rasberry-PIs/Days12-14RaspberryPiProject…  · Web viewThat’s because the names of the pins is not the name of the

Basic Web ServerCode (Python):#Ethan and Zane#8/7/14#Basic Web Server

#Importsfrom flask import Flask #Web Framework

#Creates flask object called appapp = Flask(__name__) #two underscores in front, two in back(for all)

#Runs the below code when someone accesses the root URL of the [email protected]("/")def hello(): return "Hello World!"

#If this script was run directly from the command line:if __name__ == "__main__": #Have the server listen on port 80 and report any errors app.run(host = '0.0.0.0', port = 80, debug = True)

Notes:You need to download a Python web framework called Flask to turn the Raspberry Pi into a dynamic web server. To install Flask, you need to have pip installed:Type into the terminal:sudo apt-get install python-pipAfter it is installed, type in:sudo pip install flask to install Flask

In order to view the IP address of the Pi, type in:ifconfig into the terminal. The IP address is the one after inet addr:

Type in the IP address into another computer on the same network and you should read “Hello World!”

Page 12: Days 12-14: Raspberry Pi Project.docxfaculty.cse.tamu.edu/.../Rasberry-PIs/Days12-14RaspberryPiProject…  · Web viewThat’s because the names of the pins is not the name of the

Basic Web API PageCode (Python):#Ethan and Zane#8/7/14#Basic Server + API

#Importsfrom flask import Flask #Web Frameworkimport requests #Internet requests

#Server#Creates flask object called appapp = Flask(__name__)

#API#Need a key from weather underground to use APIkey = '<Your key here>’'

#The url that we are looking at. Conditions in Saratoga SpringsapiUrl = 'http://api.wunderground.com/api/' + key +'/conditions/q/NY/Saratoga_Springs.json'

r = requests.get(apiUrl) #Gets data at the url

#The file type is a .json.#This converts the file into something that the program can useforecast = r.json

#current temp in ftemp = forecast['current_observation']['temp_f']

#server#Runs the below code when someone accesses the [email protected]("/")def hello(): return "Current tempature in Saratoga Springs is " + str(temp) + "degrees F"

Page 13: Days 12-14: Raspberry Pi Project.docxfaculty.cse.tamu.edu/.../Rasberry-PIs/Days12-14RaspberryPiProject…  · Web viewThat’s because the names of the pins is not the name of the

#If this script was run directly from the command line:if __name__ == "__main__": #Have the server listen on port 80 and report any errors app.run(host = '0.0.0.0', port = 80, debug = True)

Note:This code is just a combination of the previous two: basic API and basic Web Server. It will print the current temp in Saratoga Springs to the web page at the IP address of the Raspberry Pi

Page 14: Days 12-14: Raspberry Pi Project.docxfaculty.cse.tamu.edu/.../Rasberry-PIs/Days12-14RaspberryPiProject…  · Web viewThat’s because the names of the pins is not the name of the

Basic Web TemplateCode (Python):#Ethan and Zane#8/7/14#Hello Template#Importsfrom flask import Flask, render_templateimport datetime

app = Flask(__name__)@app.route("/")def hello(): now = datetime.datetime.now() timeString = now.strftime("%y-%m-%d %H:%M") templateData = { 'title' : 'HELLO!', 'time' : timeString } return render_template('main.html', **templateData)

if __name__ == "__main__": app.run(host = '0.0.0.0', port = 80, debug = True)

Code (html):<!DOCTYPE html> <head> <title>{{ title }}</title> </head>

<body> <h1>Hello, World!</h1> <h2>The date and time on the server is: {{ time }}</h2> </body></html>

Note:For this project you need to files, one python (similar to the last few), and one for the html template. The html file needs to be saved inside of a file called templates, and the folder should be in the same directory as the python program. The html is a template that the python program can use to generate a program. In the html, the {{ title }} will replace be replaced with the variable called title in the python program, which can be changed by the python program. render_template is a function that will create the webpage from the main.html template and the templateData, which is created directly above with the two variables (title and time). Project from Getting Started with Raspberry Pi - O'reilly and Make

Page 15: Days 12-14: Raspberry Pi Project.docxfaculty.cse.tamu.edu/.../Rasberry-PIs/Days12-14RaspberryPiProject…  · Web viewThat’s because the names of the pins is not the name of the

Challenge: Control LEDs Over InternetCode (Python):#Ethan and Zane#8/7/14

#Importsimport RPi.GPIO as GPIO #Outputfrom flask import Flask, render_template, request #Connect to internet

app = Flask(__name__)

GPIO.setmode(GPIO.BOARD)

pins = { 7: {'name': 'LED1', 'state' :GPIO.LOW}, #Attached to pin 7 12: {'name': 'LED2', 'state' :GPIO.LOW}, #Attached to pin 12 16: {'name': 'LED3', 'state' :GPIO.LOW}, #Attached to pin 16 18: {'name': 'LED3', 'state' :GPIO.LOW} #Attached to pin 18}

for pin in pins: GPIO.setup(pin, GPIO.OUT) GPIO.output(pin, GPIO.LOW)

@app.route("/")def main(): for pin in pins: pins[pin]['state'] = GPIO.input(pin) templateData = { 'pins' : pins } return render_template('main.html', **templateData)

@app.route("/<changePin>/<action>")def action(changePin, action): changePin = int(changePin) deviceName = pins[changePin]['name']

Page 16: Days 12-14: Raspberry Pi Project.docxfaculty.cse.tamu.edu/.../Rasberry-PIs/Days12-14RaspberryPiProject…  · Web viewThat’s because the names of the pins is not the name of the

if action == "on": GPIO.output(changePin, 1) message = "Turned " + deviceName + " on." if action == "off": GPIO.output(changePin, GPIO.LOW) message = "Turned " + deviceName + " off." if action == "toggle": GPIO.output(changePin, not GPIO.input(changePin)) message = "Toggled " + deviceName + "."

for pin in pins: pins[pin]['state'] = GPIO.input(pin)

templateData = { 'message' : message, 'pins' : pins }

return render_template('main.html', **templateData)

if __name__ == "__main__": app.run(host = '0.0.0.0', port = 80, debug = True)

GPIO.cleanup()

Code (html):<!DOCTYPE html><head> <title>Current Status</title>

Page 17: Days 12-14: Raspberry Pi Project.docxfaculty.cse.tamu.edu/.../Rasberry-PIs/Days12-14RaspberryPiProject…  · Web viewThat’s because the names of the pins is not the name of the

</head>

<body> <h1>Device Listing and Status</h1>

{% for pin in pins %} <p>The {{ pins[pin].name }} {% if pins[pin].state == true %} is currently on (<a href="/{{pin}}/off">turn off</a>) {% else %} is currently off (<a href="/{{pin}}/on">turn on</a>) {% endif %} </p> {% endfor %}

{% if message %} <h2>{{ message }}</h2> {% endif %}

</body></html>

Note:This challenge is a composition of the other basic projects above it. You have to have installed all the libraries in the terminal. If you want to add more LEDs, just add a line in the pins = {} object:PinNumber: {'name': 'LED', 'state': GPIO.LOW}

There are very few comments because frankly, we didn’t have time to figure it out ourselves. Just run the code and love it. We got the code from Getting Started with Raspberry Pi - O'reilly and Make