Basics of Raspberry Pi
Table of Contents
Raspberry Pi 3 Hardware Spec
Raspberry Pi 3 vs. Arduino
Setup of the Raspberry Pi
Step 1: Plug in a monitor (via HDMI) and a keyboard and mouse (via USB)
Step 2: Get an operating system
Installing an Operating System
Requires memorization for efficiency
The console or terminal is a text entry and display device
Accounts
Man(ual) Pages
Hierarchy of directories and files
pwd
cd
ls
mkdir, rmdir
nano
Viewing a File
cp
mv
File Permissions
Viewing File Permissions
Root Account
Python Language
High-level language, easy to use
Slow compared to C, C++
Two versions : Python 2.x and Python 3.x
Run Python Code
Algebraic Expressions
>>> 2 + 2
4
>>> 8 - 5
3
>>> 2*(3 + 2)
10
>>> 7/2
3.5
Boolean Expressions
>>> 2 < 4
True
>>> 1 > 3
False
>>> 2 == 4
False
>>> 2 != 3
True
>>> 1 <= 3
True
>>> 2 >= 4
False
Boolean Operators
>>> 2 < 3 and 3 < 4
True
>>> 4 == 5 and 3 < 4
False
>>> False and True
False
>>> Ture and True
True
>>> 4 == 5 or 3 < 4
True
>>> False or Ture
True
>>> False or False
False
>>> not(3 < 4)
False
Variables, Assignments
>>> x = 3
>>> x
3
>>> 4 * x
12
>>> y = 4 * x
>>> y
12
Strings
>>> 'Hello, World'
'Hello, World'
>>> s = 'still'
>>> t = 'life'
String Operators
Operator | Definition |
---|---|
x in s | x is a substring of s |
x not in s | x is not a substring of s |
s + t | Concatenation of s and t |
s n, n s | Concatenation of n copies of s |
s[i] | Character at index i of s |
len(s) | (function) Length of string s |
>>> 'Hello, World!'
'Hello, World!'
>>> s = 'still'
>>> t = 'life'
>>> s == 'still'
True
>>> s != t
True
>>> s < t
False
>>> s > t
True
String Operator Examples
>>> s = 'still'
>>> t = 'life'
>>> s + t
'stilllife'
>>> s + ' ' + t
'still life'
>>> 5 * s
'stillstillstillstillstill'
>>> 20 * '_'
'____________________'
>>> 'i' in s
True
>>> 'o' in t
False
>>> 'li' in t
True
>>> len(t)
4
Indexing Operator
>>> s = 'Apple'
>>> s[0]
'A'
>>> s[1]
'p'
>>> s[4]
'e'
>>> def test():
print ('A test function')
>>> test()
A test function
>>>
Function Parameters/Arguments
>>> def circle_area(rad):
print (3.14 * rad * rad)
>>> circle_area(2)
12.56
Function Return Values
>>> def circle_area(rad):
return 3.14 * rad * rad
>>> circle_area(2)
12.56
>>> 3 + circle_area(2)
15.56
Lists
>>> pets = ['ant', 'bat', 'cod', 'dog']
>>> lst = [0, 1, 'two', [4, 'five']]
>>> nums = [0, 1, 2, 3, 4, 5, 6, 7, 8]
List Operators and Functions
Operator | Definition |
---|---|
x in lst | x is an item of lst |
x not in lst | x is not an item of lst |
lst + lstB | Concatenation of lst and lstB |
lstn, nlst | Concatenation of n copies of lst |
lst[i] | Item at index i of lst |
len(lst) | Number of items in lst |
min(lst) | Minimum item in lst |
max(lst) | Maximum item in lst |
sum(lst) | Sum of items in lst |
List Methods
>>> lst = [1, 2, 3]
>>> lst.append(8)
>>> lst
List Methods
Method | Definition |
---|---|
lst.append(item) | adds item to the end of lst |
lst.count(item) | returns the number of times item occurs in lst |
lst.index(item) | Returns index of (first occurrence of) item in lst |
lst.pop() | Removes and returns the last item in lst |
lst.remove(item) | Removes (the first occurrence of) item from lst |
lst.reverse(item) | Reverses the order of items in lst |
lst.sort(item) | Sorts the items of lst in increasing order |
Control Flow
If statement
if <condition>:
<indented code block>
<non-indented statement>
if temp > 80:
print ('It is hot!')
print ('Goodbye.')
If-else statement
if <condition>:
<indented code 1>
else :
<indented code 2>
<non-indented statement>
if temp > 80:
print ('hot!')
else:
print ('not hot.')
print ('Goodbye.')
For Loop
>>> name = 'Ian'
>>> for char in name:
print(char)
I
a
n
>>>
For Example
>>> for name in ['Jon', 'Mary', 'Pete']:
print(name)
Jon
Mary
Pete
>>>
While Loop
>>> i = 0
>>> while i < 3:
print (i)
i = i + 1
0
1
2
>>>
Errors During Execution
Handling Exceptions
try:
z = x / y
except ZeroDivisionError:
print("Divide by zero")
import
import RPi.GPIO as GPIO
Pin Direction and Assignment
GPIO.setup(13, GPIO.OUT)
pinMode(13, OUTPUT)
for ArduinoGPIO.output(13, True)
digitalWrite(11, HIGH)
for Arduinoimport RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(13, GPIO.OUT)
while True:
GPIO.output(13, True)
time.sleep(1)
GPIO.output(13, False)
time.sleep(1)
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(18, GPIO.IN)
while True:
if GPIO.input(18) == 1:
print("Button Pressed")
time.sleep(0.5)
else:
print("Button Unpressed")
time.sleep(0.5)
Pulse Width Modulation
PWM initialization
pwm_obj = GPIO.PWM(18, 400)
- Mark pin for PWM
- Second argument is frequency
pwm_obj.start(100)
- Start generating PWM signal
- Argument is duty cycle, 0 to 100
PWM Control
pwm_obj.ChangeDutyCycle(50)
Frequency Control
while True:
GPIO.output(18, True)
time.sleep(0.5)
GPIO.output(18, False)
time.sleep(0.5)
PWM Example
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(13, GPIO.OUT)
pwm = GPIO.PWM(13, 50)
pwm.start(0)
for i in range(100):
pwm.ChangeDutyCycle(i)
time.sleep(0.1)
for i in range(100, 0, -1):
pwm.ChangeDutyCycle(i)
time.sleep(0.5)
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(13, GPIO.OUT)
pwm = GPIO.PWM(13, 50)
pwm.start(0)
for i in range(100):
pwm.ChangeDutyCycle(i)
time.sleep(0.1)
for i in range(100, 0, -1):
pwm.ChangeDutyCycle(i)
time.sleep(0.5)
Servo Motors
Servo Control
Servo Motor Wiring
Servo Motor Power
Servo Wiring
Servo Example 1
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.OUT)
pwm = GPIO.PWM(12, 50)
pwm.start(0)
for i in range(100)
pwm.ChangeDutyCycle(i)
print(i)
time.sleep(0.5)
for i in range(100, 0, -1):
pwm.ChangeDutyCycle(i)
print(i)
time.sleep(0.5)
Servo Example 2
import RPi.GPIO as GPIO
import numpy as np
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(8, GPIO.OUT)
pwm = GPIO.PWM(8, 50)
pwm.start(0)
while True:
for i in np.arange(2.5, 12.5, 0.1):
pwm.ChangeDutyCycle(i)
time.sleep(0.1)
for i in np.arange(12.5, 2.5,-0.1):
pwm.ChangeDutyCycle(i)
time.sleep(0.1)
#!/usr/bin/python
import smbus
import math
import time
import os
# Power management registers
power_mgmt_1 = 0x6b
power_mgmt_2 = 0x6c
def read_byte(adr):
return bus.read_byte_data(address, adr)
def read_word(adr):
high = bus.read_byte_data(address, adr)
low = bus.read_byte_data(address, adr+1)
val = (high << 8) + low
return val
def read_word_2c(adr):
val = read_word(adr)
if (val >= 0x8000):
return -((65535 - val) + 1)
else:
return val
def dist(a,b):
return math.sqrt((a*a)+(b*b))
def get_y_rotation(x,y,z):
radians = math.atan2(x, dist(y,z))
return -math.degrees(radians)
def get_x_rotation(x,y,z):
radians = math.atan2(y, dist(x,z))
return math.degrees(radians)
bus = smbus.SMBus(1) # or bus = smbus.SMBus(1) for Revision 2 boards
address = 0x68 # This is the address value read via the i2cdetect command
# Now wake the 6050 up as it starts in sleep mode
bus.write_byte_data(address, power_mgmt_1, 0)
while True:
os.system('cls' if os.name == 'nt' else 'clear')
print("gyro data")
print("---------")
gyro_xout = read_word_2c(0x43)
gyro_yout = read_word_2c(0x45)
gyro_zout = read_word_2c(0x47)
print("gyro_xout: ", gyro_xout)
print("scaled : ", (gyro_xout / 131))
print("gyro_yout: ", gyro_yout)
print("scaled : ", (gyro_yout / 131))
print("gyro_zout: ", gyro_zout)
print("scaled : ", (gyro_zout / 131))
print()
print("accelerometer data")
print("------------------")
accel_xout = read_word_2c(0x3b)
accel_yout = read_word_2c(0x3d)
accel_zout = read_word_2c(0x3f)
accel_xout_scaled = accel_xout / 16384.0
accel_yout_scaled = accel_yout / 16384.0
accel_zout_scaled = accel_zout / 16384.0
print("accel_xout: ", accel_xout)
print("scaled : ", accel_xout_scaled)
print("accel_yout: ", accel_yout)
print("scaled : ", accel_yout_scaled)
print("accel_zout: ", accel_zout)
print("scaled : ", accel_zout_scaled)
print()
print("x rotation: " , get_x_rotation(accel_xout_scaled, accel_yout_scaled, accel_zout_scaled))
print("y rotation: " , get_y_rotation(accel_xout_scaled, accel_yout_scaled, accel_zout_scaled))
time.sleep(0.5)
# Simple example of reading the MCP3008 analog input channels and printing
# them all out.
# Author: Tony DiCola
# License: Public Domain
import time
# Import SPI library (for hardware SPI) and MCP3008 library.
import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008
# Software SPI configuration:
CLK = 18
MISO = 23
MOSI = 24
CS = 25
mcp = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI)
# Hardware SPI configuration:
# SPI_PORT = 0
# SPI_DEVICE = 0
# mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))
print('Reading MCP3008 values, press Ctrl-C to quit...')
# Print nice channel column headers.
print('| {0:>4} | {1:>4} | {2:>4} | {3:>4} | {4:>4} | {5:>4} | {6:>4} | {7:>4} |'.format(*range(8)))
print('-' * 57)
# Main program loop.
while True:
# Read all the ADC channel values in a list.
values = [0]*8
for i in range(0, 3):
# The read_adc function will get the value of the specified channel (0-3).
values[i] = mcp.read_adc(i)
# Print the ADC values.
print('| {0:>4} | {1:>4} | {2:>4} | {3:>4} | {4:>4} | {5:>4} | {6:>4} | {7:>4} |'.format(*values))
# Pause for half a second.
time.sleep(0.1)
import threading
import time
def every_second(msg):
i = 0
while True:
time.sleep(1)
i += 1
print(msg, i)
def every_five_second(msg):
i = 0
while True:
time.sleep(5)
i += 5
print(msg, i)
t1 = threading.Thread(target = every_second, args = ("t1 :",))
t2 = threading.Thread(target = every_five_second, args = ("t2 :",))
t1.daemon = True
t2.daemon = True
t1.start()
t2.start()
while True:
pass
Raspberry Pi Camera Module
Enabling the Camera
raspi-config
to enable the CSI interface
sudo raspi-config
python-picamera Library
sudo apt-get updata
sudo apt-get install python3picamera
picamera
import picamera
camera = picamera.PiCamera()
Camera Functions
camera.capture("pict.jpg")
camera.hflip = True
camera.vflip = True
camera.brightness = 50
camera.sharpness = 0
camera.start_preview()
camera.stop_preview()
Video Recording
import picamera
import time
camera.start_recording("vid.h264")
time.sleep(10)
camera.stop_recording()
Sending an Image on the Network
mysocket = socket.socket()
mysocket.connect(('aserver', 8000))
conn = mysocket.makefile('wb')
camera.capture(conn, 'jpeg')
Timelapse Photography
Continuous Capture
camera = picamera.PiCamera()
for filename in camera.capture_continuous('img(counter).jpg'):
time.sleep(300)
Example
import picamera
camera = picamera.PiCamera()
camera.capture('test_image.jpg')
%%javascript
$.getScript('https://kmahelona.github.io/ipython_notebook_goodies/ipython_notebook_toc.js')