外接按鈕控制
===

## 上拉電阻


```python=
#!/usr/bin/python
#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#|R|a|s|p|b|e|r|r|y|P|i|.|c|o|m|.|t|w|
#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# Copyright (c) 2016, raspberrypi.com.tw
# All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# push_button_poll.py
# Response when push button is pressed with poll way
#
# Author : sosorry
# Date : 06/22/2014
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
BTN_PIN = 11
GPIO.setup(BTN_PIN, GPIO.IN)
previousStatus = None
try:
while True:
input = GPIO.input(BTN_PIN)
if input == GPIO.LOW and previousStatus == GPIO.HIGH:
print("Button pressed @", time.ctime())
previousStatus = input
except KeyboardInterrupt:
print("Exception: KeyboardInterrupt")
finally:
GPIO.cleanup()
```
# 輪詢與中斷
上面這個程式的 CPU 用量挺大的(2x%)
$ top -c
### 輪詢 (polling)
SoC 每隔一段時間檢查週邊硬體的資料
### 中斷 (interrupt)
當週邊硬體的狀態改變時 , 對 SoC 發出中斷要求
### 建立回呼函數
def mycallback()
### 綁定事件和回呼函數
add_event_detect(gpio, # 對象
edge, # 觸發條件
callback, #回呼函數
bouncetime)
```python=
#!/usr/bin/python
#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#|R|a|s|p|b|e|r|r|y|P|i|.|c|o|m|.|t|w|
#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# Copyright (c) 2016, raspberrypi.com.tw
# All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# push_button_interrupt.py
# Response when push button is pressed with interrupt way, and de-bounces
# by software
#
# Author : sosorry
# Date : 06/22/2014
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
BTN_PIN = 11
WAIT_TIME = 200
GPIO.setup(BTN_PIN, GPIO.IN)
def mycallback(channel):
print("Button pressed @", time.ctime())
try:
GPIO.add_event_detect(BTN_PIN, GPIO.FALLING, callback=mycallback, bouncetime=WAIT_TIME)
while True:
time.sleep(10)
except KeyboardInterrupt:
print("Exception: KeyboardInterrupt")
finally:
GPIO.cleanup()
```
# 小夜燈

```python=
LED_PIN = 22
GPIO.setup(LED_PIN, GPIO.OUT)
if GPIO.input(LED_PIN)==GPIO.HIGH:
GPIO.output(LED_PIN, GPIO.LOW)
else :
GPIO.output(LED_PIN, GPIO.HIGH)
```