際際滷

際際滷Share a Scribd company logo
http://blog.xcoda.net
Raspberry Pi GPIO
with Python
Rev. R610
伎語 (dltpdn@gmail.com)
http://blog.xcoda.net
Raspberry-Pi
碁覈谿
1. Introduction
2. Rasbian Installation
3. Development Environment
4. GPIO
5. Digital Output
6. Digital Input
7. Analog Output  PWM
8. Sensor Modules
9. ADC-SPI
10. Sound
11. Camera
http://blog.xcoda.net
Raspberry-Pi
Introduction
 Raspberry-Pi
 https://en.wikipedia.org/wiki/Raspberry_Pi
 蟲 殊覯襴 , Eben Upton
 蟲 螳覦蟲 貉危 螻狩 蟲 讀讌 覈
 2011  覲企
 2012 豌 襷
 觚襦貉 BCM2835 SoC
 PC 狩蟆
http://blog.xcoda.net
Raspberry-Pi
Introduction
 Raspberry Pi Boards
 https://www.raspberrypi.org/products/
Model A Model A+
Model B
Raspberry Pi 2 Raspberry Pi 3 Raspberry Pi Zero
Model B+
http://blog.xcoda.net
Raspberry-Pi
Introduction
 Raspberry Pi 3
 ARMv8 CPU 1.2GHz 64bit quad-core
 802.11n Wireless LAN
 Bluetooth 4.1
 Bluetooth Low Energy(BLE)
 1GB RAM
 4 USB ports
 40 GPIO Pins
 Full HDMI port
 Ethernet port
 3.5mm audio
 Camera interface(CSI)
 Display interface(DSI)
 Micro SD card slot
 VideoCore IV 3D graphics core
http://blog.xcoda.net
Raspberry-Pi
碁覈谿
1. Introduction
2. Rasbian Installation
3. Development Environment
4. GPIO
5. Digital Output
6. Digital Input
7. Analog Output  PWM
8. Sensor Modules
9. ADC-SPI
10. Sound
11. Camera
http://blog.xcoda.net
Raspberry-Pi
Rasbian Installation
 Rasbian Installation
 OS image file download
 https://www.raspberrypi.org/downloads/raspbian/
 Raspbian Jessie, Jessi Lite
 Image file SD豺企 覲旧
 http://sourceforge.net/projects/win32diskimager/
 Win32 Disk Imager
 USB-Serial console 郁屋  蟆曙
 Serial console tty 燕
 Config.txt 殊 豢螳
 enable_uart=1
 Core_req=250
 Direct Lan Cable 郁屋  蟆曙
 Cmdline.txt  rootwait れ 豢螳
 Ip=192.168.0.2
 SD豺企襯 覲企 蠎所  瑚
 Putty襦 Serial  IP襦 襦蠏語
 ID : pi
 PWD : raspberry
http://blog.xcoda.net
Raspberry-Pi
Rasbian Installation
 LCD Monitor setup
 http://elinux.org/index.php?title=RPiconfig
 /boot/config.txt
 PC 覦伎れ 
 Max_usb_current
 Usb 豢  覲蟆
 600mA 1200mA
 Hdmi_group
 1 : CEA, 2: DMT
 Hdmi_mode=87
 Custom mode
 Hdmi_cvt
 width, height, framerate, aspect, margins, interlace, rb
max_usb_current=1
hdmi_group=2
hdmi_mode=87
hdmi_cvt=1024 600 60 6 0 0 0
http://blog.xcoda.net
Raspberry-Pi
Rasbian Installation
 蠍磯蓋れ
 Sudo raspi-config
 1 Expand Filesystem
 5 Internationalisation options
 Time Zone > Asia > Seoul
 Change Locale
 en_US.UTF-8
 ko_KR.EUC-KR
 ko_KR.UTF-8
 Default : en_US.UTF-8
 sudo apt-get update
 sudo apt-get upgrade
http://blog.xcoda.net
Raspberry-Pi
Rasbian Installation
 Static IP setup
 sudo vi /etc/dhcpcd.conf (覦煙 )
 sudo reboot
 Ifconfig eth0
 Wifi setup
 sudo iwlist wlan0 scan
 sudo vi /etc/wpa_supplicatn/wpa_supplicant.conf
 Sudo ifdown wlan0
 Sudo ifup wlan0
 Ifconfig wlan0
interface eth0
static ip_address=192.168.0.xx
static routers=192.168.0.254
static domain_name_servers=8.8.8.8
Network={
ssid=my_ap
psk=my_password
}
http://blog.xcoda.net
Raspberry-Pi
碁覈谿
1. Introduction
2. Rasbian Installation
3. 螳覦 蟆
4. GPIO
5. Digital Output
6. Digital Input
7. Analog Output  PWM
8. Sensor Modules
9. ADC-SPI
10. Sound
11. Camera
http://blog.xcoda.net
Raspberry-Pi
螳覦 蟆
 JDK れ
 Eclipse  伎 
 http://java.sun.com
 http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-
2133151.html
http://blog.xcoda.net
Raspberry-Pi
螳覦 蟆
 Eclipse れ
 http://www.eclipse.org/downloads/
 Eclipse IDE for JavaEE Developer
http://blog.xcoda.net
Raspberry-Pi
螳覦 蟆
 Python れ
 https://www.python.org/downloads/release/python-2711/
 2.7 覯 れ
http://blog.xcoda.net
Raspberry-Pi
螳覦 蟆
 PyDev れ
 Eclipse > Help > Eclipse Marketplace
 Python 蟆
http://blog.xcoda.net
Raspberry-Pi
螳覦 蟆
 PyDev setup
 Eclipse Preferences
 Pydev > Interpreters > Python Interpreter
 Quick Auto-Config
http://blog.xcoda.net
Raspberry-Pi
螳覦 蟆
 襦 
 New > Project
 New > PyDev Module
http://blog.xcoda.net
Raspberry-Pi
螳覦 蟆
 貊  覦 ろ
 壱企Ν > Run As > Python Run
print Hello raspberry Pi
http://blog.xcoda.net
Raspberry-Pi
螳覦 蟆
 RemoteSystem れ
 Eclipse > Window > Perspective > Open Perspective > Other
http://blog.xcoda.net
Raspberry-Pi
螳覦 蟆
 RemoteSystem れ
 Remote System >  企Ν
http://blog.xcoda.net
Raspberry-Pi
螳覦 蟆
 襦蠏語
http://blog.xcoda.net
Raspberry-Pi
螳覦 蟆
 蟆 
 PyDev Perspective 燕 襦 Export
 Remote Systems > Remote File System
http://blog.xcoda.net
Raspberry-Pi
螳覦 蟆
 蟆 
 Raspberry-pi 襴
http://blog.xcoda.net
Raspberry-Pi
螳覦 蟆
 蟆 
 Description file
http://blog.xcoda.net
Raspberry-Pi
螳覦 蟆
 蟆 
 Synchronize View襦 蟆
http://blog.xcoda.net
Raspberry-Pi
螳覦 蟆
 蟆 
 磯碁襦 伎 ろ
http://blog.xcoda.net
Raspberry-Pi
碁覈谿
1. Introduction
2. Rasbian Installation
3. Development Environment
4. GPIO
5. Digital Output
6. Digital Input
7. Analog Output  PWM
8. Advanced I/O
9. ADC-SPI
10. Sound
11. Camera
http://blog.xcoda.net
Raspberry-Pi
GPIO
 GPIO Pin Header
http://blog.xcoda.net
Raspberry-Pi
GPIO
 GPIO 
 Sysfs
 襴 貉る 2.6+
 轟  ろ
 GPIO  企ゼ  殊企 
 磯碁 讌 譟一
 System call 伎 C 襦蠏碁覦
 譴 C 襦蠏碁覦
 BCM 28xx 讌ろ 蠏
 Soc 一危  谿語^
 C 殊企襴
 Wiring-pi
 http://wiringpi.com/ (Gordon)
 BCM2835
 http://www.airspayce.com/mikem/bcm2835/
http://blog.xcoda.net
Raspberry-Pi
GPIO
 Python GPIO Modules
 Rpi.GPIO
 https://pypi.python.org/pypi/RPi.GPIO
 https://sourceforge.net/projects/raspberry-gpio-python/ (Ben Croston)
 Raspberry Pi 蠍磯蓋 れ
  
 GPIO Software PWM襷 讌
 れ螳 危襴貅伎 覿
 WiringPi-Python
 https://github.com/WiringPi/WiringPi-Python
 C語企 蟲 WringPi wrapped version
 Arduino style 貊襯 讌
 GPIO, Serial, SPI, I2C, Hardware PWM   蠍磯 覈 
 WriginPi Library 譬
 Raspberry-Pi build/install
http://blog.xcoda.net
Raspberry-Pi
GPIO
 Sysfs襯 伎 貊 覈
$ echo 18 > /sys/class/gpio/export
$ ls /sys/class/gpio/
$ echo out > /sys/class/gpio/gpio18/direction
$ echo 1 > /sys/class/gpio/gpio18/value
$ echo 0 > /sys/class/gpio/gpio18/value
$ echo 18 > /sys/class/gpio/unexport
$ ls /sys/class/gpio/
http://blog.xcoda.net
Raspberry-Pi
GPIO
 Sysfs襯 伎 C Program  gpioled.c
sprintf(buff, "/sys/class/gpio/gpio%d/direction" ,
gpio_pin);
fd = open(buff, O_WRONLY);
if (fd == -1) {
perror("fail to open GPIO Direction File" );
return 1;
}
if (write (fd, "out" , 4) == -1) {
perror("fail to set directionn" );
return 1;
}
close(fd);
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main( int argc, char **argv) {
int gpio_pin = 18;
int fd;
char buff[BUFSIZ];
fd = open("/sys/class/gpio/export", O_WRONLY );
if (fd == -1) {
perror("fail to open export." );
return 1;
}
sprintf(buff, "%d" , gpio_pin);
if (write (fd, buff, sizeof(buff)) == -1) {
perror("fail to export GPIO" );
return 1;
}
close(fd);
http://blog.xcoda.net
Raspberry-Pi
GPIO
 Sysfs襯 伎 C Program <螻>
fd = open("/sys/class/gpio/unexport" , O_WRONLY );
sprintf(buff, "%d" , gpio_pin);
write(fd, buff, strlen(buff));
close(fd);
return 0;
}
sprintf(buff, "/sys/class/gpio/gpio%d/value" , gpio_pin);
fd = open(buff, O_WRONLY);
int i=0;
for(i=0; i<10; i++) {
if (write (fd, "1" , sizeof("1")) == -1) {
perror("fail to set value:1" );
return 1;
}
printf("set gpio %d value as HIGHn", gpio_pin);
sleep(1);
if (write (fd, "0" , sizeof("0")) == -1) {
perror("fail to set value:0" );
return 1;
}
printf("set gpio %d value as LOWn", gpio_pin);
sleep(1);
}
close(fd);
$ gcc o gpioled gpioled.c
$ sudo ./gpioled
http://blog.xcoda.net
Raspberry-Pi
GPIO
 Wiring-Pi
 れ
 sudo apt-get install git-core
 Git clone git://git.drogon.net/wiringPi
 Cd wiringPi
 ./build
 Gpio 覈
 wiringPi襯 れ覃 gpio 覈轟   .
$ gpio -g mode 18 out
$ gpio -g write 18 1
$ gpio -g write 18 0
http://blog.xcoda.net
Raspberry-Pi
GPIO
 LED Blink Wiring-Pi Code
 Wiringpi_led.c
#include <stdio.h>
#include <stdlib.h>
#include <wiringPi.h>
#define LED 1 // BCM18
int main( void) {
puts("!!!Hello wiringPi!!!" ); /* prints !!!Hello World!!! */
int i;
wiringPiSetup();
pinMode(LED, OUTPUT);
for(i=0; i<10; i++){
digitalWrite(LED, HIGH);
printf("pin %d HIGHn" , LED);
delay(1000);
digitalWrite(LED, LOW);
printf("pin %d LOWn" , LED);
delay(1000);
}
return EXIT_SUCCESS;
}
$ gcc o wiringpi_led wiringpi_led.c lwiringPi
$ sudo ./wiringpi_led
http://blog.xcoda.net
Raspberry-Pi
GPIO
 Rpi.GPIO 蠍磯蓋 
 import Rpi.GPIO as GPIO
 覈 import
 GPIO.setmode(GPIO.BCM or GPIO.BOARD)
 GPIO.BCM : Broadcom Soc  覯
 GPIO.BOARD : 覲企  覯
 GPIO.setup(channel, direction[, intial=state] )
 channel : GPIO Pin 覯
 direction : GPIO.IN, GPIO.OUT
 state : GPIO.HIGH, GPIO.LOW
 GPIO.setup(channel, GPIO.IN [, pull_up_down=pud])
 pud = GPIO.PUD_UP, GPIO.PUD_DOWN
 GPIO.input(channel)
 GPIO.output(channel, state)
 GPIO.cleanup()
 譬襭  覦
 https://sourceforge.net/p/raspberry-gpio-python/wiki/Examples/
http://blog.xcoda.net
Raspberry-Pi
碁覈谿
1. Introduction
2. Rasbian Installation
3. Development Environment
4. GPIO
5. Digital Output
6. Digital Input
7. Analog Output  PWM
8. Sensor Modules
9. ADC-SPI
10. Sound
11. Camera
http://blog.xcoda.net
Raspberry-Pi
Digital Output
 LED Blink
 LED 蟾覦願鍵
 覿
 LED(Light Emitting Diode)
 讌ъ るΜ : Cathod(貂), 蠏( - )
 蠍 るΜ : Anode(碁), 蠏( + )
 貂 讓 襾碁Μ 襴螳 蟾 .
 (Register)
 襯 襴 覦
 ,襯 
 蠏轟 
  : (ohm, )
 襦 郁屋
 LED 蠍 るΜ : GPIO18 + 
 LED 讌ъ るΜ : GND
http://blog.xcoda.net
Raspberry-Pi
Digital Output
  螳 蟲蠍
 LED , 襯 
 Data sheet
 5mm  蠍一
 襯 20mA
   1.8V~2.2V
 伎 覯豺
 V = I * R
 R = V / I
 (螻糾  LED) / 襯
 (5  2) / 0.02 = 150
 150 蠏殊 螳   : 220
http://blog.xcoda.net
Raspberry-Pi
Digital Output
 螳 所鍵
 螻手碓  語 蠍一 覿譟
 4螳  5螳 螳 
 蠍   るジ讓曙
 4 蟆曙
 3覯讌碁 轟(0 螳)
 4覯讌碁 れ姶覯
 5 蟆曙
 4覯讌碁 轟(0 螳)
 5覯讌碁 れ姶覯
 
 螳(1),蟆(0),る讌(103), 蠍
 10,000 = 10K, 賊5%
 觜螳(2),觜螳(2),螳(101),蠍
 220, 賊5%
 る讌(3),る讌(3),螳(101), 蠍
 330, 賊5%
 螳(1), 蟆(0), 蟆(0), 碁(104), 螳
 1,000,000 = 1M ,賊1%
http://blog.xcoda.net
Raspberry-Pi
Digital Output
 Bread Board (觜牛)
 PCB 覲企襯 襷り鍵  襦
   
 覿襴 覦 譟磯 螳
 螳 企朱Μ 郁屋
 譬 碁 譴  郁屋(覯れ)
 譴 5豺語 , 覿 郁屋(IC )
http://blog.xcoda.net
Raspberry-Pi
Digital Output
 LED Blink 倬襦蟲
http://blog.xcoda.net
Raspberry-Pi
Digital Output
 LED Blink Python Code
import RPi.GPIO as GPIO
import time
led_pin = 18
try:
GPIO.setmode(GPIO.BCM)
GPIO.setup(led_pin, GPIO.OUT)
while True:
GPIO.output(led_pin, True)
time.sleep(0.5)
GPIO.output(led_pin, False)
time.sleep(0.5)
finally:
print 'clean up'
GPIO.cleanup()
http://blog.xcoda.net
Raspberry-Pi
Digital Output
 襴企 れ豺
 220V 螳 貅螻 蠍
 覲企 5V   伎 螳
  覿
 襴企 れ豺
 IN, 5V, GND
 覓伎 覦豌 襴企
 IN, GND
 220V 蠏 /
http://blog.xcoda.net
Raspberry-Pi
Digital Output
 襴企 れ豺 倬襦蟲
220V AC
http://blog.xcoda.net
Raspberry-Pi
Digital Output
 襴企 れ豺 倬襦蟲
http://blog.xcoda.net
Raspberry-Pi
Digital Output
 襴企 れ豺 Code
 LED Blink 
import RPi.GPIO as GPIO
import time
fan_pin = 18
try:
GPIO.setmode(GPIO.BCM)
GPIO.setup(fan_pin, GPIO.OUT)
while True:
val = input("1:on, 0:off")
GPIO.output(fan_pin, val)
finally:
print 'clean up'
GPIO.cleanup()
http://blog.xcoda.net
Raspberry-Pi
Digital Output
 碁讌ろ
 Transistor = Trans + Resistor
  覦豌 
 3螳 :C(Collector), B(Base), E(Emitter)
 Base  襯() 磯 企  覲
 讀 襦, れ豺 襦 
 谿 螳 
 NPN
 Base  企誤 覲企 朱 
 PNP
 Base  企誤 覲企 朱(0.6v)
http://blog.xcoda.net
Raspberry-Pi
Digital Output
 碁讌ろ れ豺
 2n2222
 襷  PNP  碁讌ろ
   襯襯 
  伎伎 碁讌ろ 覲危
 襦 蟲
 USB Connector Vcc  R-PI 5V
 USB Connector GND  Collector
 R-PI GPIO18  Base(220)
 R-PI GND - Emitter
http://blog.xcoda.net
Raspberry-Pi
Digital Output
 碁讌ろ れ豺 倬襦蟲
http://blog.xcoda.net
Raspberry-Pi
Digital Output
 碁讌ろ れ豺 Code
 LED Blink 
pin = 18
try:
GPIO.setmode(GPIO.BCM)
GPIO.setup(pin, GPIO.OUT)
while True:
val = input("swtich [on:1, off:0]")
GPIO.output(pin, val)
finally:
print 'clean up'
GPIO.cleanup()
http://blog.xcoda.net
Raspberry-Pi
碁覈谿
1. Introduction
2. Rasbian Installation
3. Development Environment
4. GPIO
5. Digital Output
6. Digital Input
7. Analog Output  PWM
8. Sensor Modules
9. ADC-SPI
10. Sound
11. Camera
http://blog.xcoda.net
Raspberry-Pi
Digital Input
 語 覯 れ豺 
 覯 れ豺襦 LED襯 貅螻 
 覯 れ豺
 螳 るΜ 覿 
 4螳 譴 2螳襷 郁屋企 .
 襦 郁屋
 13覯  LED  GND
 れ 
 5V  覯  10k   GND
 覯 - Digital 7覯
  
 5V  10k  覯  Digital 7覯
 覯  GND
http://blog.xcoda.net
Raspberry-Pi
1. Digital Input
 (Pull Up), れ(Pull Down) 
 襦(Floating) 
 れ豺螳 企れ  企 語    
 譯朱  , 蠍  ′ 豬
 れ豺螳 企れ  Vcc(5V)  0V(GND)襯 郁屋伎 願屋
 Vcc GND襯 蠏碁襦 郁屋覃 暑 螻殊襯 覓語
 朱朱 10K   願屋
  (Vcc) 郁屋覃 (Pull Up), GND 郁屋覃 れ(Pull
Down)
HIGH?
LOW?
+5V
Digital 
HIGH
+5V
Digital 
HIGH?
LOW?
GND
Digital 
LOW
GND
Digital 
LOW
GND
Digital 
+5V
HIGH
GND
Digital 
+5V
http://blog.xcoda.net
Raspberry-Pi
Digital Input
 語覯 れ豺 襦( )
http://blog.xcoda.net
Raspberry-Pi
Digital Input
 語覯 れ豺 襦(れ )
http://blog.xcoda.net
Raspberry-Pi
Digital Input
 語覯 れ豺 Code
import RPi.GPIO as GPIO
pin = 18
try:
GPIO.setmode(GPIO.BCM)
GPIO.setup(pin, GPIO.IN)
while True:
print GPIO.input(pin)
finally:
GPIO.cleanup()
http://blog.xcoda.net
Raspberry-Pi
Digital Input
 語覯 襦(企 /れ)
  企朱 螻
 GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
 GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.PUD_UP GPIO.PUD_DOWN
http://blog.xcoda.net
Raspberry-Pi
Digital Input
 語覯 れ豺 企 /れ Code
import RPi.GPIO as GPIO
pin = 18
try:
GPIO.setmode(GPIO.BCM)
#GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
while True:
print GPIO.input(pin)
finally:
GPIO.cleanup()
http://blog.xcoda.net
Raspberry-Pi
Digital Input
 Magnetic Door Switch
 覓語企 讌
 螳  覿螻 伎 磯  れ豺
  覿
   れ豺
 10K 
 Push Button 螻 狩 襦 れ豺
http://blog.xcoda.net
Raspberry-Pi
Digital Input
 LDR(Light Dependent Resistor)
 譟郁殊
 蠏 
 觜 磯 螳 覲, 螳覲
 10Lux : 20 ~ 50k
 0Lux : 2M
 襦
 1M れ 
 螳覲  轟 螳 伎/危 
 Analog 碁ゼ Digital襦 語
http://blog.xcoda.net
Raspberry-Pi
Digital Input
 LDR(譟磯殊) 倬襦蟲
http://blog.xcoda.net
Raspberry-Pi
Digital Input
 LDR(譟磯殊) Code
import RPi.GPIO as GPIO
import time
try:
pin = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(pin, GPIO.IN)
val = -1
while True:
read = GPIO.input(pin)
if read != val:
val = read
print time.strftime("%Y%m%d-%H%M%S"), val
#time.sleep(0.1)
finally:
print "clean up."
GPIO.cleanup()
http://blog.xcoda.net
Raspberry-Pi
Digital Input
 語 殊(Infrared Sensor)
 語 覦蠍(IRED)
 Infrared Emitting Diode
 LED 覈
 朱朱 襴覈貊  覿覿 レ逢
 ′朱 觜 覲  
 豺企 觀壱碁襦  螳
  襯 : 100mA
   : 1.3v ~ 1.7v
   : 5v 朱 35
 (5  1.5)v / 0.1A = 35
http://blog.xcoda.net
Raspberry-Pi
Digital Input
 語 殊(Infrared Sensor)
 語 蠍(Photo Transistor)
 語  磯ジ 碁讌ろ
 語 螳 磯 Collector-Emitter  覲
 Pull-down  1MEmitter(-)
Collector(+)
http://blog.xcoda.net
Raspberry-Pi
Digital Input
 語 殊 倬襦蟲
http://blog.xcoda.net
Raspberry-Pi
Digital Input
 語 殊 Code
import RPi.GPIO as GPIO
import time
try:
pin = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(pin, GPIO.IN)
val = -1
while True:
read = GPIO.input(pin)
if read != val:
val = read
print time.strftime("%Y%m%d-%H%M%S"), val
#time.sleep(0.1)
finally:
print "clean up."
GPIO.cleanup()
http://blog.xcoda.net
Raspberry-Pi
Digital Input
  螳讌蠍
 譯朱 讌企 蟆 讌 螳讌
  讌企 LED 貅讌
  覿
 Passive Infrared, PIR 殊
 1 : Out
 2: Vcc
 3: GND
 4:
 H: Repeatable
 L : Unrepeatable
 5 : latency , 0.5s ~ 50s
http://blog.xcoda.net
Raspberry-Pi
Digital Input
 PIR 殊 Code
import RPi.GPIO as GPIO
import time
from datetime import datetime
pri_pin = 18
try:
GPIO.setmode(GPIO.BCM)
GPIO.setup(pri_pin, GPIO.IN)
val = -1
while True:
read = GPIO.input(pri_pin)
if val != read:
val = read
if val== 0:
print str(datetime.now()), "No intruder"
elif val == 1:
print str(datetime.now()), "Intruder dectected"
time.sleep(0.5)
finally:
print 'clean up'
GPIO.cleanup()
http://blog.xcoda.net
Raspberry-Pi
Digital Input
 一 殊
 /給 殊襯 覈襦 蟲
 3
 Red : Vcc (3~5V)
 Green : Data Out
 Black : GND
  Digital Input
http://blog.xcoda.net
Raspberry-Pi
Digital Input
 一 殊 Code
import time
import datetime
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
pad_pin = 5
GPIO.setup(pad_pin, GPIO.IN)
while True:
pad_pressed = GPIO.input(pad_pin)
if pad_pressed:
current_datetime = datetime.datetime.now().strftime("%I:%M%p:%S on %B %d, %Y")
print("pressed! - " + current_datetime)
time.sleep(0.1)
http://blog.xcoda.net
Raspberry-Pi
碁覈谿
1. Introduction
2. Rasbian Installation
3. Development Environment
4. GPIO
5. Digital Output
6. Digital Input
7. Analog Output  PWM
8. Sensor Modules
9. ADC-SPI
10. Sound
11. Camera
http://blog.xcoda.net
Raspberry-Pi
Analog Output  PWM
 Analog Out
 PWM( Pulse Width Modulation)   覲譟
 讌 譯狩 れ  譟一 襦蠏 碁 
 譯狩(Frequency) : Hz, 1豐 殊企 れ 螳
 譯手鍵(Period) :  れ 讌 螳
 Pulse Width :  Period 燕 蠍郁
 Duty Cycle :  譯手鍵 伎 HIGH  螳 觜
http://blog.xcoda.net
Raspberry-Pi
Analog Output  PWM
 Analog Out
 Raspberry-Pi PWM
 Hardware PWM : BCM2835 SoC
 讌ろ AL0
 GPIO12,13  PWM0, PWM1
 讌ろ AL1
 GPIO18, 19  PWM0, PWM1
 Software PWM : Wiring-Pi Libarary
 GPIO  
  伎
 LED Fading
 GPIO18
http://blog.xcoda.net
Raspberry-Pi
Analog Output  PWM
 LED Fade 襦 蟲
http://blog.xcoda.net
Raspberry-Pi
Analog Output  PWM
 LED Fade Code
import RPi.GPIO as GPIO
import time
try:
pin = 26
GPIO.setmode(GPIO.BCM)
GPIO.setup(pin, GPIO.OUT)
pwm = GPIO.PWM(pin, 100)
pwm.start(0)
while True:
for i in range(0, 101):
pwm.ChangeDutyCycle(i)
time.sleep(0.05)
for i in range(100, -1, -1):
pwm.ChangeDutyCycle(i)
time.sleep(0.05)
finally:
pwm.stop()
GPIO.cleanup()
http://blog.xcoda.net
Raspberry-Pi
Analog Output  PWM
 Servo Motor
 180尊  螳
 螳 覲  螳
 PWM れ 讌螳朱 
 0.5ms : -90尊
 1.5ms : 0尊
 2.5ms : +90尊
http://blog.xcoda.net
Raspberry-Pi
Analog Output  PWM
 Servo Motor 襦 蟲
http://blog.xcoda.net
Raspberry-Pi
Analog Output  PWM
 Servo Motor Code
 Frequency : 100Hz
 1豐(1000ms) 100Hz
 1Period = 10ms(1000/100)
 -90尊 : 0.5ms
 1Period 5%
 0.5 / 10
 0尊 : 1.5ms
 1Period 15%
 1.5 / 10
 +90尊 : 2.5ms
 1Period 25%
 2.5 / 10
import RPi.GPIO as GPIO
import time
pin = 25
try:
GPIO.setmode(GPIO.BCM)
GPIO.setup(pin, GPIO.OUT)
p = GPIO.PWM(pin,100)
p.start(5)
while True:
p.ChangeDutyCycle(5) #-90degree
time.sleep(1)
p.ChangeDutyCycle(15) #0 dgree
time.sleep(2)
p.ChangeDutyCycle(25) #+90 degree
time.sleep(1)
p.ChangeDutyCycle(15) #0 dgree
time.sleep(2)
except KeyboardInterrput:
p.stop()
GPIO.cleanup()
http://blog.xcoda.net
Raspberry-Pi
碁覈谿
1. Introduction
2. Rasbian Installation
3. Development Environment
4. GPIO
5. Digital Output
6. Digital Input
7. Analog Output  PWM
8. Sensor Modules
9. ADC-SPI
10. Sound
11. Camera
http://blog.xcoda.net
Raspberry-Pi
Sensor Modules
 豐 蟇磯Μ 殊
 HC SR-04
 Vcc : 5v
 Trigger : GPIO 24 , 豐 覦
 Echo : GPIO 23, 覦  語
 GND : Ground
 豐襯 覦貅 覦 螳朱 蟇磯Μ襯 螻
 Trigger pin 10us  HIGH
 8覯 40hz 豐  覦
 Echo pin Low
  覦 譴
 Echo pin HIGH 
  覦 譬襭
 Echo pin LOW 
 覦  
  螳
 HIGH   螳
http://blog.xcoda.net
Raspberry-Pi
Sensor Modules
 豐 蟇磯Μ 殊 Source
 螳朱 蟇磯Μ 螻
  : 340m/s, 34000cm/s
 34000 = distance / time
 34000 = distance / (time/2)
 覲 螳
 17000 = distance / time
 17000 * time = distance
trig_pin = 24
echo_pin = 23
try:
GPIO.setmode(GPIO.BCM)
GPIO.setup(trig_pin, GPIO.OUT)
GPIO.setup(echo_pin, GPIO.IN)
while True:
GPIO.output(trig_pin, False)
print "ready for mesurement."
time.sleep(0.2)
GPIO.output(trig_pin, True)
time.sleep(0.00001) #set HIGH for 10us
GPIO.output(trig_pin, False)
while GPIO.input(echo_pin) == 0:
start_time = time.time()
while GPIO.input(echo_pin) == 1:
end_time = time.time()
travel_time = end_time - start_time;
distance = travel_time * 17150 #32300/2
distance = round(distance, 2)
print 'Distance:%dcm' %distance
finally:
GPIO.cleanup()
http://blog.xcoda.net
Raspberry-Pi
Sensor Modules
 DHT-11 /給 覈
 /給 殊襯 覈襦 蟲
 3
 Red : Vcc (3~5V)
 Green : Data Out
 Black : GND
 1Wire 旧
 譯殊伎 旧 豌願 襷豢  
 MCU 豌瑚 覃 
 HIGH 覯 讌 螳 磯 0, 1 蟲覿
 40bit 一危(給: 16bit, : 16bit, CheckSum: 8bit
 Real-time  覃 旧 ろ  
 Rpi.GPIO襦 蟲 蟆  ろ
 http://www.uugear.com/portfolio/dht11-humidity-temperature-sensor-module/
http://blog.xcoda.net
Raspberry-Pi
Sensor Modules
 DHT-11 /給 覈
 豌 
 HIGHLOW  PULL_UP
 0 :26~28us HIGH, 1: 70us HIGH
http://blog.xcoda.net
Raspberry-Pi
Sensor Modules
 DHT-11 /給 覈
 40bit  一危
 16bit 給 (: 652  65.2%)
 8bit : 給  觜 (0000 0010)
 8bit : 給  觜 (1000 1100)
 16bit  (: 351  35.1尊)
 8bit :   觜 (0000 0001)
 8bit :   觜 (0101 1111)
 8bit : Check Sum (: 1110 1110)
0000 0010
+ 1000 1100
+ 0000 0001
+ 0101 1111
http://blog.xcoda.net
Raspberry-Pi
Sensor Modules
 DHT-11 Source
 Rpi.GPIO襦 蟲
 https://github.com/netikras/r-pi_DHT11/blob/master/dht11.py
def pullData():
global data
global effectiveData
global pin
data = []
effectiveData = []
GPIO.setup(pin,GPIO.OUT)
GPIO.output(pin,GPIO.HIGH)
time.sleep(0.025)
GPIO.output(pin,GPIO.LOW)
time.sleep(0.14)
GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
for i in range(0,1000):
data.append(GPIO.input(pin))
import RPi.GPIO as GPIO
import time
import sys
def bin2dec(string_num):
return str(int(string_num, 2))
data = []
effectiveData = []
bits_min=999;
bits_max=0;
HumidityBit = ""
TemperatureBit = ""
crc = ""
crc_OK = False;
Humidity = 0
Temperature = 0
pin=4
GPIO.setmode(GPIO.BCM)
http://blog.xcoda.net
Raspberry-Pi
Sensor Modules
 DHT-11 Source
 Rpi.GPIO襦 蟲 <螻>
for i in range(0, 40):
buffer = "";
while(seek < len(data) and data[seek] == 0):
seek+=1;
while(seek < len(data) and data[seek] == 1):
seek+=1;
buffer += "1";
if (len(buffer) < bits_min):
bits_min = len(buffer)
if (len(buffer) > bits_max):
bits_max = len(buffer)
effectiveData.append(buffer);
def analyzeData():
seek=0;
bits_min=9999;
bits_max=0;
global HumidityBit
global TemperatureBit
global crc
global Humidity
global Temperature
HumidityBit = ""
TemperatureBit = ""
crc = ""
while(seek < len(data) and data[seek] == 0):
seek+=1;
while(seek < len(data) and data[seek] == 1):
seek+=1;
http://blog.xcoda.net
Raspberry-Pi
Sensor Modules
 DHT-11 Source
 Rpi.GPIO襦 蟲 <螻>
def isDataValid():
global Humidity
global Temperature
global crc
print "isDataValid(): H=%d, T=%d, crc=%d"% (int(Humidity),
int(Temperature), int(bin2dec(crc)))
if int(Humidity) + int(Temperature) == int(bin2dec(crc)):
return True;
else:
return False;
def printData():
global Humidity
global Temperature
print "H: "+Humidity
print "T: "+Temperature
for i in range(0, len(effectiveData)):
if (len(effectiveData[i]) < ((bits_max + bits_min)/2)):
effectiveData[i] = "0";
else:
effectiveData[i] = "1";
for i in range(0, 8):
HumidityBit += str(effectiveData[i]);
for i in range(16, 24):
TemperatureBit += str(effectiveData[i]);
for i in range(32, 40):
crc += str(effectiveData[i]);
Humidity = bin2dec(HumidityBit)
Temperature = bin2dec(TemperatureBit)
http://blog.xcoda.net
Raspberry-Pi
Sensor Modules
 DHT-11 Source
 Rpi.GPIO襦 蟲 <螻>
while (not crc_OK):
pullData();
analyzeData();
if (isDataValid()):
crc_OK=True;
print "r",
printData();
else:
sys.stderr.write(".")
time.sleep(2);
http://blog.xcoda.net
Raspberry-Pi
Sensor Modules
 DHT-11 Source
 Adafruit DHT 覈 
 https://learn.adafruit.com/dht/overview
import Adafruit_DHT
sensor = Adafruit_DHT.DHT11
pin = 7
while True:
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
if humidity is not None and temperature is not None:
print "Temp={0:0.1f}*C Humidity={1:0.1f}%".format(temperature, humidity)
else:
print "Failed to get reading."
git clone https://github.com/adafruit/Adafruit_Python_DHT.git
http://blog.xcoda.net
Raspberry-Pi
碁覈谿
1. Introduction
2. Rasbian Installation
3. Development Environment
4. GPIO
5. Digital Output
6. Digital Input
7. Analog Output  PWM
8. Sensor Modules
9. ADC-SPI
10. Sound
11. Camera
http://blog.xcoda.net
Raspberry-Pi
ADC - SPI
 襦磯Μ 螳覲(Rotary Potentiometer)
 ′企ゼ  螳 覲蟆
 Pin1 : 5V, Pin2 : OUT, Pin3 : GND
 螳覲  豢レ 伎伎 LED Fading
http://blog.xcoda.net
Raspberry-Pi
ADC - SPI
 讌旧 Vs 覲旧
 讌(Serial) 旧
  觜碁ゼ 谿朱 
 螳 襴
 旧  1螳
 覲(Parallel) 旧
   觜碁ゼ 
 螳 觜襯企
 旧   觜  襷
http://blog.xcoda.net
Raspberry-Pi
ADC - SPI
 讌旧
 一危襯  觜語 谿朱 
 企   觜語語 蟲覿  覦覯 
 ′ 螳 觜 蟲覿   覦
 觜蠍一(Asynchronus) 讌旧
 一危 蟲覿 譯手鍵襯 襦 曙
 企 碁ゼ 磯 覲企伎 
 螳 旧螳 襷讌 朱 旧 覿
 觜語 讌觜瑚 豢螳襦 
 1:1 旧襷 螳
 RS-232(UART) 旧 襦貊 
 蠍一(Synchronus) 讌旧
 一危 語 觜 蟲覿(Clock)襯 覲襦 
 企 襷豢一 一危  語
 螳  曙 覿
 豕螻  
 1:N 旧 螳,
 Master/Slave 蟯螻, Master螳 企 譯朱
 I2C, SPI 旧 襦貊
http://blog.xcoda.net
Raspberry-Pi
ADC - SPI
 SPI(Serial Peripheral Interconnect) 旧
 蠍一 讌旧
 覈襦る殊  螳覦
 旧  : 4
 SCK, SCLK(Serial Clock) : 襷ろ郁 企 
 MOSI(Master Output Slave Input) : 襷ろ 
 MISO(Master Input Slave Output) : 襷ろ 
 SS(Slave Select) : 襷ろ郁 企 
 企 レ 襷 螻 1 豢螳
  企襷 '0', 襾語 '1'
 れ 旧  2螳(MOSI, MISO)
 伎 旧,   觜襴
 SPI Mode
  觜(0,1) ,企 觜(0,1) れ
http://blog.xcoda.net
Raspberry-Pi
ADC - SPI
 MCP3008
 ADC (Analog Digital Convertor)
 10bit 伎 (0~ 1023)
 SPI 旧
 螳覲  Analog 碁ゼ  れ
 襦郁屋
 Vdd  3.3v
 Vref  3.3v
 AGND  GND
 CLK  CLK(GPIO11)
 Dout  MISO(GPIO09)
 Din  MOSI(GPIO10)
 CS - CE0(GPIO08)
 CH0  螳覲 OUT
http://blog.xcoda.net
Raspberry-Pi
ADC - SPI
 螳覲 MCP3008襦 所鍵
http://blog.xcoda.net
Raspberry-Pi
ADC - SPI
 SPI 燕 覦 覈 れ
 Raspberry-pi SPI  燕
 sudo raspi-config
 8.Advanced Options > SPI > Yes
 ls /dev/spi*
 Py-spidev 覈 れ
 spidev  覈 (/dev/spidev0.0 , /dev/spidev0.1)
 https://github.com/doceme/py-spidev
 git clone git://github.com/doceme/py-spidev
 cd py-spidev
 Sudo python setup.py install
 
 Pip install py-spidev
http://blog.xcoda.net
Raspberry-Pi
ADC - SPI
 MCP3008 旧
 http://www.farnell.com/datasheets/808965.pdf
 3Byte(24bit) /
 
 1: Start bit : 1
 2: Channel configuration
 3: Ignored
 
 1: Ignored
 2-3 : 10bit value
http://blog.xcoda.net
Raspberry-Pi
ADC - SPI
 MCP3008襦 螳覲 所鍵
 open(port, dev)
 Port : 0
 Dev :CE0 =0, CE1=1
 xfer2([byte_1, byte_2, byte_3])
 byte_1 : 1
 byte_2 : channel config
 1000 000 : channel 0
 byte_3 : 0(ignored)
 abc_out
 r[0] : ignored
 r[1] : 10bit 豕 2bit 螳
 r[2] : 10bit  8bit 螳
import spidev, time
spi = spidev.SpiDev()
spi.open(0,0)
def analog_read(channel):
r = spi.xfer2([1, (8 + channel) << 4, 0])
adc_out = ((r[1]&3) << 8) + r[2]
return adc_out
try:
while True:
reading = analog_read(0)
voltage = reading * 3.3 / 1024
print("Reading=%dtVoltage=%f" % (reading,
voltage))
time.sleep(1)
finally:
spi.close()
http://blog.xcoda.net
Raspberry-Pi
碁覈谿
1. Introduction
2. Rasbian Installation
3. Development Environment
4. GPIO
5. Digital Output
6. Digital Input
7. Analog Output  PWM
8. Sensor Modules
9. ADC-SPI
10. Sound
11. Camera
http://blog.xcoda.net
Raspberry-Pi
Sound
 Buzzer
 Digital output
  覿
 覿 ろ殊擦  Piezo
 螳覲(覲朱エ譟一)
 WiringPi-Python 覈襦襷 螳
 https://github.com/WiringPi/WiringPi-Python
 れ
 git clone --recursive https://github.com/WiringPi/WiringPi-Python.git
 sudo apt-get install python-dev python-setuptools swig
 cd WiringPi-Python
 ./build.sh
 softToneCreate(PIN)
 豢 GPIO Pin 覯
 softToneWrite(PIN, FREQUENCY)
 豢ロる 譯狩 螳 讌
http://blog.xcoda.net
Raspberry-Pi
Sound
 語  襦 蟲
http://blog.xcoda.net
Raspberry-Pi
Sound
 蟆暑慨 豢
import wiringpi
from time import sleep
pin = 24
wiringpi.wiringPiSetupGpio()
try:
wiringpi.softToneCreate(pin)
while True:
wiringpi.softToneWrite(pin, 392)
sleep(0.1)
wiringpi.softToneWrite(pin, 523)
sleep(0.1)
finally:
wiringpi.pinMode(pin, 0)
http://blog.xcoda.net
Raspberry-Pi
Sound
 覦讌覦讌 覲 れ豺
import wiringpi
from time import sleep
pin = 24
frequencies = {'c':262, 'd':294, 'e':330, 'f':349, 'g':392, 'a':440, 'b':494}
notes = 'ccggaag ffeeddc ggffeed ggffeed ccggaag ffeeddc'
wiringpi.wiringPiSetupGpio()
try:
wiringpi.softToneCreate(pin)
for i in notes:
if i != ' ':
wiringpi.softToneWrite(pin, frequencies[i])
sleep(0.3)
finally:
wiringpi.pinMode(pin, 0)
http://blog.xcoda.net
Raspberry-Pi
Sound
 Speaker
 Audio Enable
 /boot/config.txt
 Dtparam=audio=on
 れ Audio 豢 覈
 https://wiki.python.org/moin/Audio/
 Pygame mixer 覈
 http://www.pygame.org/docs/ref/music.html
 import pygame
 pygame.init()
 pygame.mixer.music.load(sample.mp3)
 pygame.mixer.music.play()
 pygame.mixer.music.pause()
 pygame.mixer.music.unpause()
 pygame.mixer.music.stop()
http://blog.xcoda.net
Raspberry-Pi
Sound
 Pygame mixer code
import pygame
import time
pygame.init()
#pygame.mixer.music.load("sample.wav")
pygame.mixer.music.load("sample.mp3")
while True:
cmd = raw_input("cmd{play:p, pause:pp, unpause:up, stop:s} :")
if cmd == "p":
pygame.mixer.music.play()
elif cmd == "pp":
pygame.mixer.music.pause()
elif cmd == "up":
pygame.mixer.music.unpause()
elif cmd == "s":
pygame.mixer.music.stop()
# exit(0)
else:
print "incorrect cmd. try again."
http://blog.xcoda.net
Raspberry-Pi
碁覈谿
1. Introduction
2. Rasbian Installation
3. Development Environment
4. GPIO
5. Digital Output
6. Digital Input
7. Analog Output  PWM
8. Sensor Modules
9. ADC-SPI
10. Sound
11. Camera
http://blog.xcoda.net
Raspberry-Pi
Camera
 Raspi-Camera
 https://www.raspberrypi.org/documentation/usage/camera/python/README.md
 Camera Interface 郁屋
 殊覯襴 豺企 燕
 sudo raspi-config
 6. Enable Camera
 Pycamera 覈 れ
 https://github.com/waveform80/picamera
 sudo apt-get install python-pycamera
 讌 覦   襴 
 mkdir ~/camera
 豐  play
 omxplayer path/file.h264
http://blog.xcoda.net
Raspberry-Pi
Camera
 Pycamera Code
import time
import picamera
with picamera.PiCamera() as camera:
try:
camera.start_preview()
while True:
shutter = input('insert key when you are ready to take photo. [photo:1, video:2] ')
now_str = time.strftime("%Y%m%d-%H%M%S")
if shutter == 1:
camera.capture('/home/pi/demo/camera/photo%s.gif' %now_str)
elif shutter == 2:
camera.start_recording('/home/pi/demo/camera/video%s.h264' %now_str)
raw_input('insert key when you want to stop recoding.')
camera.stop_recording()
finally:
camera.stop_preview()

More Related Content

Raspberry-PI GPIO with Python