KEMBAR78
Raspberry-PI GPIO with Python | PPTX
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 저항 1MΩEmitter(-)
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 온도/습도 모듈
 요청 신호
 HIGHLOW  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()

Raspberry-PI GPIO with Python

  • 1.
    http://blog.xcoda.net Raspberry Pi GPIO withPython Rev. R610 이세우 (dltpdn@gmail.com)
  • 2.
    http://blog.xcoda.net Raspberry-Pi 세부목차 1. Introduction 2. RasbianInstallation 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
  • 3.
    http://blog.xcoda.net Raspberry-Pi Introduction  Raspberry-Pi  https://en.wikipedia.org/wiki/Raspberry_Pi 영국 라즈베리파이 재단, Eben Upton  학교와 개발도상국 컴퓨터 과학 교육 증진 목표  2011 알파 보드  2012 첫 판매  브로드컴 BCM2835 SoC  PC와 동일하게 사용
  • 4.
    http://blog.xcoda.net Raspberry-Pi Introduction  Raspberry PiBoards  https://www.raspberrypi.org/products/ Model A Model A+ Model B Raspberry Pi 2 Raspberry Pi 3 Raspberry Pi Zero Model B+
  • 5.
    http://blog.xcoda.net Raspberry-Pi Introduction  Raspberry Pi3  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
  • 6.
    http://blog.xcoda.net Raspberry-Pi 세부목차 1. Introduction 2. RasbianInstallation 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
  • 7.
    http://blog.xcoda.net Raspberry-Pi Rasbian Installation  RasbianInstallation  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
  • 8.
    http://blog.xcoda.net Raspberry-Pi Rasbian Installation  LCDMonitor 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
  • 9.
    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
  • 10.
    http://blog.xcoda.net Raspberry-Pi Rasbian Installation  StaticIP 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” }
  • 11.
    http://blog.xcoda.net Raspberry-Pi 세부목차 1. Introduction 2. RasbianInstallation 3. 개발 환경 4. GPIO 5. Digital Output 6. Digital Input 7. Analog Output – PWM 8. Sensor Modules 9. ADC-SPI 10. Sound 11. Camera
  • 12.
    http://blog.xcoda.net Raspberry-Pi 개발 환경  JDK설치  Eclipse 동작을 위해서 필요  http://java.sun.com  http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads- 2133151.html
  • 13.
    http://blog.xcoda.net Raspberry-Pi 개발 환경  Eclipse설치  http://www.eclipse.org/downloads/  Eclipse IDE for JavaEE Developer
  • 14.
    http://blog.xcoda.net Raspberry-Pi 개발 환경  Python설치  https://www.python.org/downloads/release/python-2711/  2.7 버전 설치
  • 15.
    http://blog.xcoda.net Raspberry-Pi 개발 환경  PyDev설치  Eclipse > Help > Eclipse Marketplace  Python 검색
  • 16.
    http://blog.xcoda.net Raspberry-Pi 개발 환경  PyDevsetup  Eclipse Preferences  Pydev > Interpreters > Python Interpreter  Quick Auto-Config
  • 17.
    http://blog.xcoda.net Raspberry-Pi 개발 환경  프로젝트생성  New > Project  New > PyDev Module
  • 18.
    http://blog.xcoda.net Raspberry-Pi 개발 환경  코드작성 및 실행  우클릭 > Run As > Python Run print “Hello raspberry Pi”
  • 19.
    http://blog.xcoda.net Raspberry-Pi 개발 환경  RemoteSystem설정  Eclipse > Window > Perspective > Open Perspective > Other
  • 20.
  • 21.
  • 22.
    http://blog.xcoda.net Raspberry-Pi 개발 환경  원격적용  PyDev Perspective에서 생성한 프로젝트 Export  Remote Systems > Remote File System
  • 23.
    http://blog.xcoda.net Raspberry-Pi 개발 환경  원격적용  Raspberry-pi 디렉토리 선택
  • 24.
  • 25.
    http://blog.xcoda.net Raspberry-Pi 개발 환경  원격적용  Synchronize View로 원격 적용
  • 26.
    http://blog.xcoda.net Raspberry-Pi 개발 환경  원격적용  터미널로 접속해서 실행
  • 27.
    http://blog.xcoda.net Raspberry-Pi 세부목차 1. Introduction 2. RasbianInstallation 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
  • 28.
  • 29.
    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/
  • 30.
    http://blog.xcoda.net Raspberry-Pi GPIO  Python GPIOModules  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 필요
  • 31.
    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/
  • 32.
    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);
  • 33.
    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
  • 34.
    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
  • 35.
    http://blog.xcoda.net Raspberry-Pi GPIO  LED BlinkWiring-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
  • 36.
    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/
  • 37.
    http://blog.xcoda.net Raspberry-Pi 세부목차 1. Introduction 2. RasbianInstallation 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
  • 38.
    http://blog.xcoda.net Raspberry-Pi Digital Output  LEDBlink  LED 깜박이기  부품  LED(Light Emitting Diode)  짧은 다리 : Cathod(캐소드), 음극( - )  긴 다리 : Anode(애노드), 양극( + )  캐소드 쪽 머리 테두리가 깍여 있다.  저항(Register)  전류의 흐름을 방해  전압,전류 저하  전극이 없음  단위 : Ω(ohm, 옴)  회로 연결  LED 긴 다리 : GPIO18 + 저항  LED 짧은 다리 : GND
  • 39.
    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Ω
  • 40.
    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%
  • 41.
    http://blog.xcoda.net Raspberry-Pi Digital Output  BreadBoard (빵판)  PCB 보드를 만들기 전 프로토타입  납땜할 필요 없음  분리 및 재조립 가능  같은 열끼리 연결  좌우 세로 줄 전원 연결(버스영역)  중앙 5칸씩 , 부품 연결(IC 영역)
  • 42.
  • 43.
    http://blog.xcoda.net Raspberry-Pi Digital Output  LEDBlink 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()
  • 44.
    http://blog.xcoda.net Raspberry-Pi Digital Output  릴레이스위치  220V 가전제품 켜고 끄기  보드의 5V 전원 제어 이외 가전제품  필요 부품  릴레이 스위치  IN, 5V, GND  무접점 반도체 릴레이  IN, GND  220V 플러그 암/수
  • 45.
  • 46.
  • 47.
    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()
  • 48.
    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) 동작
  • 49.
    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
  • 50.
  • 51.
    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()
  • 52.
    http://blog.xcoda.net Raspberry-Pi 세부목차 1. Introduction 2. RasbianInstallation 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
  • 53.
    http://blog.xcoda.net Raspberry-Pi Digital Input  푸쉬버튼 스위치 입력  버튼 스위치로 LED를 켜고 끔  버튼 스위치  두개의 다리는 붙어 있다  4개 중 2개만 연결해도 된다.  회로 연결  13번 – LED – GND  풀다운 저항  5V – 버튼 – 10k 저항 – GND  버튼 - Digital 7번  풀업 저항  5V – 10k저항 – 버튼 – Digital 7번  버튼 – GND
  • 54.
    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
  • 55.
  • 56.
  • 57.
    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()
  • 58.
    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
  • 59.
    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()
  • 60.
    http://blog.xcoda.net Raspberry-Pi Digital Input  MagneticDoor Switch  문열림 탐지  두개의 자석이 붙고 떨어짐에 따라 동작하는 스위치  필요 부품  자석 도어 스위치  10KΩ 저항  Push Button 과 동일한 회로와 스케치 사용
  • 61.
    http://blog.xcoda.net Raspberry-Pi Digital Input  LDR(LightDependent Resistor)  조광센서  양음극 없음  빛에 따라 저항값 변화, 가변저항  10Lux : 20 ~ 50kΩ  0Lux : 2MΩ  회로  1MΩ 풀다운 저항  가변적인 전압의 특정 값 이상/이하 입력  Analog 신호를 Digital로 인식
  • 62.
  • 63.
    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()
  • 64.
    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
  • 65.
    http://blog.xcoda.net Raspberry-Pi Digital Input  적외선센서(Infrared Sensor)  적외선 수신기(Photo Transistor)  적외선 수신에 따른 트랜지스터  적외선 값에 따라 Collector-Emitter 저항 변화  Pull-down 저항 1MΩEmitter(-) Collector(+)
  • 66.
  • 67.
    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()
  • 68.
    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
  • 69.
    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()
  • 70.
    http://blog.xcoda.net Raspberry-Pi Digital Input  터치센서  온도/습도 센서를 모듈로 구성  3핀  Red : Vcc (3~5V)  Green : Data Out  Black : GND  단순한 Digital Input
  • 71.
    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)
  • 72.
    http://blog.xcoda.net Raspberry-Pi 세부목차 1. Introduction 2. RasbianInstallation 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
  • 73.
    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 상태 시간 비율
  • 74.
    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
  • 75.
  • 76.
    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()
  • 77.
    http://blog.xcoda.net Raspberry-Pi Analog Output –PWM  Servo Motor  180º 회전 가능  각도 별 제어 가능  PWM 펄스의 지속시간으로 제어  0.5ms : -90º  1.5ms : 0º  2.5ms : +90º
  • 78.
  • 79.
    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()
  • 80.
    http://blog.xcoda.net Raspberry-Pi 세부목차 1. Introduction 2. RasbianInstallation 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
  • 81.
    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 상태인 동안의 시간
  • 82.
    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()
  • 83.
    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/
  • 84.
    http://blog.xcoda.net Raspberry-Pi Sensor Modules  DHT-11온도/습도 모듈  요청 신호  HIGHLOW  PULL_UP  0 :26~28us HIGH, 1: 70us HIGH
  • 85.
    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
  • 86.
    http://blog.xcoda.net Raspberry-Pi Sensor Modules  DHT-11Source  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)
  • 87.
    http://blog.xcoda.net Raspberry-Pi Sensor Modules  DHT-11Source  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;
  • 88.
    http://blog.xcoda.net Raspberry-Pi Sensor Modules  DHT-11Source  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)
  • 89.
    http://blog.xcoda.net Raspberry-Pi Sensor Modules  DHT-11Source  Rpi.GPIO로 구현 <계속> while (not crc_OK): pullData(); analyzeData(); if (isDataValid()): crc_OK=True; print "r", printData(); else: sys.stderr.write(".") time.sleep(2);
  • 90.
    http://blog.xcoda.net Raspberry-Pi Sensor Modules  DHT-11Source  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
  • 91.
    http://blog.xcoda.net Raspberry-Pi 세부목차 1. Introduction 2. RasbianInstallation 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
  • 92.
    http://blog.xcoda.net Raspberry-Pi ADC - SPI 로터리 가변저항(Rotary Potentiometer)  손잡이를 돌려 저항값 변경  Pin1 : 5V, Pin2 : OUT, Pin3 : GND  가변 저항 출력을 이용해서 LED Fading
  • 93.
    http://blog.xcoda.net Raspberry-Pi ADC - SPI 직렬통신 Vs 병렬통신  직렬(Serial) 통신  여러 비트를 순차적으로 전송  속도가 느리다  통신 회선은 1개  병렬(Parallel) 통신  동시에 여러 비트를 전송  속도가 빠르다  통신 회선은 전송 비트 수 만큼 필요
  • 94.
    http://blog.xcoda.net Raspberry-Pi ADC - SPI 직렬통신  데이타를 한 비트씩 순차적으로 전송  어느 시점을 한 비트인지 구분 할 방법 필요  송수신자 간 비트 구분 시점에 대한 방식  비동기적(Asynchronus) 직렬통신  데이타 구분 주기를 서로 약속  클럭 신호를 따로 보내지 않음  양단간 통신속도가 맞지 않으면 통신 불능  시작비트와 정지비트가 추가로 필요  1:1 통신만 가능  RS-232(UART) 통신 프로토콜이 대표적  동기적(Synchronus) 직렬통신  데이타 신호와 비트 구분신호(Clock)를 별도로 전송  클럭에 마춰서 데이타 신호 인식  양단간 속도 약속 불필요  최고 속도 제한  1:N 통신 가능,  Master/Slave 관계, Master가 클럭 주도  I2C, SPI 통신 프로토콜이 대표적
  • 95.
    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) 설정
  • 96.
    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
  • 97.
  • 98.
    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
  • 99.
    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
  • 100.
    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()
  • 101.
    http://blog.xcoda.net Raspberry-Pi 세부목차 1. Introduction 2. RasbianInstallation 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
  • 102.
    http://blog.xcoda.net Raspberry-Pi Sound  Buzzer  Digitaloutput  필요 부품  부저 스피커 또는 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)  출력하려는 주파수 값 지정
  • 103.
  • 104.
    http://blog.xcoda.net Raspberry-Pi Sound  경보음 출력 importwiringpi 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)
  • 105.
    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)
  • 106.
    http://blog.xcoda.net Raspberry-Pi Sound  Speaker  AudioEnable  /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()
  • 107.
    http://blog.xcoda.net Raspberry-Pi Sound  Pygame mixercode 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."
  • 108.
    http://blog.xcoda.net Raspberry-Pi 세부목차 1. Introduction 2. RasbianInstallation 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
  • 109.
    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
  • 110.
    http://blog.xcoda.net Raspberry-Pi Camera  Pycamera Code importtime 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()