官網地址:http://gpiozero.readthedocs.io/en/stable/recipes.htmlhtml
環境:UbuntuMeta-16.04python
樹莓派:3代B型react
二、基本方法(Basic Recipes)shell
下面演示了GPIO Zero庫的一些功能,注意的是這些方法都是在python3下編寫的,在python2下可能有用也可能沒有用!app
2.1 導入GPIO Zerodom
使用GPIO Zero庫有兩種方式函數
2.1.1 單獨導入GPIO Zero庫的某個類oop
導入 GPIO Zero 的 Button :post
from gpiozero import Button
如今 Button 就能夠直接在腳本中使用:學習
button = Button(2) #2爲Button的引腳
2.1.2 完整導入GPIO Zero庫
或者,導入整個GPIO Zero庫:
import gpiozero
在這種狀況下,GPIO Zero中對項目的全部引用都必須加上前綴(gpiozero):
button = gpiozero.Button(2) #2爲Button的引腳
2.2. Pin 編號
該庫使用Broadcom(BCM)引腳編號做爲GPIO引腳,而不是物理(BOARD)編號。 與RPi.GPIO庫不一樣,這是不可配置的。
2.3 開關一個LED
不斷的打開和關閉LED燈
from gpiozero import LED from time import sleep red = LED(17) #led的正極接GPIO17 while True: red.on() #開燈 sleep(1) red.off() #關燈 sleep(1)
或者也能夠兩一種寫法:
from gpiozero import LED from signal import pause red = LED(17) #led的正極接GPIO17
red.blink() #閃爍
pause()
2.4 改變LED的亮度
任何常規LED均可以使用PWM(脈衝寬度調製)設置其亮度值。 在GPIO Zero中,能夠使用PWMLED來實現,PWMLED的值從0到1:
from gpiozero import PWMLED from time import sleep led = PWMLED(17) while True: led.value = 0 # 滅 sleep(1) led.value = 0.5 # 半亮 sleep(1) led.value = 1 # 全亮 sleep(1)
相似於連續閃爍,PWMLED能夠脈衝(連續淡入和淡出),如下實現呼吸燈的效果:
from gpiozero import PWMLED from signal import pause led = PWMLED(17) led.pulse() #呼吸燈的效果 pause()
2.5 加入一個按鈕
按鈕的鏈接以下圖
檢查是否按下了按鈕:
from gpiozero import Button button = Button(2) while True: if button.is_pressed: print("按鈕已經按下") else: print("按鈕沒有被按下")
一直等待按鈕被按下:
from gpiozero import Button button = Button(2) button.wait_for_press() #等待按鈕被按下
print("按鈕已經按下")
每次按下按鈕的時候運行一個方法:
from gpiozero import Button from signal import pause def say_hello(): print("Hello!") button = Button(2) button.when_pressed = say_hello #當被按下時執行 say_hello 方法,注意不能寫爲say_hello()
pause()
一樣的,按鈕被釋放時也能夠執行一個方法:
from gpiozero import Button from signal import pause def say_hello(): print("Hello!") def say_goodbye(): print("Goodbye!") button = Button(2) button.when_pressed = say_hello #當被按下時執行 say_hello 方法
button.when_released = say_goodbye #當被釋放時執行 say_goodbye 方法
pause()
2.6 使用一個按鈕控制led燈
按下按鈕時打開LED:
from gpiozero import LED, Button from signal import pause led = LED(17) #定義一個led燈 button = Button(2) #定義一個button button.when_pressed = led.on #開燈 button.when_released = led.off #關燈 pause()
或者:
from gpiozero import LED, Button from signal import pause led = LED(17) #定義一個led燈
button = Button(2) #定義一個button
led.source = button.values
pause()
2.7 按鈕控制攝像頭
當按下按鈕時觸發 PiCamera 拍照,使用 when_pressed = camera.capture 的寫法是無效,由於capture()方法須要輸出參數。
可是,這能夠使用不須要參數的自定義函數來實現:
from gpiozero import Button from picamera import PiCamera from datetime import datetime from signal import pause button = Button(2) camera = PiCamera() def capture(): ctime = datetime.now().isoformat() camera.capture('/home/pi/%s.jpg' % ctime) #保存圖片 button.when_pressed = capture pause()
另外能夠使用一個按鈕來啓動和中止相機預覽,另外一個按鈕用來拍照:
from gpiozero import Button from picamera import PiCamera from datetime import datetime from signal import pause left_button = Button(2) right_button = Button(3) camera = PiCamera() def capture(): ctime = datetime.now().isoformat() camera.capture('/home/pi/%s.jpg' % ctime) left_button.when_pressed = camera.start_preview left_button.when_released = camera.stop_preview right_button.when_pressed = capture pause()
2.8 實現按鈕關機
Button類還提供了在按鈕按住一段給定時間後運行函數的功能。
下面的示例是,當按鈕按住2秒時,將關閉樹莓派:
from gpiozero import Button from subprocess import check_call from signal import pause def shutdown(): check_call(['sudo', 'poweroff']) #運行shell shutdown_btn = Button(17, hold_time=2) #定義按鈕,以及持續時間 shutdown_btn.when_held = shutdown pause()
2.9 LEDBoard(燈組)
能夠使用LEDBoard訪問LED組合燈:
from gpiozero import LEDBoard from time import sleep from signal import pause leds = LEDBoard(5, 6, 13, 19, 26) #定義一組led燈,該組由引腳分別爲5, 6, 13, 19, 26的5個led組成 leds.on() #全亮 sleep(1) leds.off() #全滅 sleep(1) leds.value = (1, 0, 1, 0, 1) #1,3,5亮,2,4滅 sleep(1) leds.blink() #所有閃爍 pause()
使用帶有pwm = True的LEDBoard,能夠控制每一個LED的亮度:
from gpiozero import LEDBoard from signal import pause leds = LEDBoard(5, 6, 13, 19, 26, pwm=True) leds.value = (0.2, 0.4, 0.6, 0.8, 1.0) #單獨設置每一個led的亮度 pause()
在高級LEDBoard方法中,能夠看到更多LEDBoard示例。
2.10 LEDBarGraph(柱狀圖)
能夠使用LEDBarGraph將LED組合爲柱狀圖:
from gpiozero import LEDBarGraph from time import sleep graph = LEDBarGraph(5, 6, 13, 19, 26, pwm=False) #定義一組led柱狀燈,該組由引腳分別爲5, 6, 13, 19, 26的5個led組成,不設置每一個燈的亮度
#如下值,相似於電量100%顯示 graph.value = 1/10 # (0.5, 0, 0, 0, 0) sleep(1) graph.value = 3/10 # (1, 0.5, 0, 0, 0) sleep(1) graph.value = -3/10 # (0, 0, 0, 0.5, 1) sleep(1) graph.value = 9/10 # (1, 1, 1, 1, 0.5) sleep(1) graph.value = 95/100 # (1, 1, 1, 1, 0.75) sleep(1)
能夠看到上面的值都是四捨五入的,當pwm = False(默認值)時,LED要麼是打開要麼是關閉。
可是,使用帶有pwm = True的LEDBarGraph能夠使用LED亮度得到更精確的值:
from gpiozero import LEDBarGraph from time import sleep graph = LEDBarGraph(5, 6, 13, 19, 26, pwm=True) #定義一組led柱狀燈,該組由引腳分別爲5, 6, 13, 19, 26的5個led組成,設置每一個燈的亮度 graph.value = 1/10 # (0.5, 0, 0, 0, 0) sleep(1) graph.value = 3/10 # (1, 0.5, 0, 0, 0) sleep(1) graph.value = -3/10 # (0, 0, 0, 0.5, 1) sleep(1) graph.value = 9/10 # (1, 1, 1, 1, 0.5) sleep(1) graph.value = 95/100 # (1, 1, 1, 1, 0.75) sleep(1)
2.11 Traffic Lights(交通燈)
一個交通燈系統。
使用像Pi-Stop這樣的TrafficLights套件:
from gpiozero import TrafficLights from time import sleep lights = TrafficLights(2, 3, 4) #一組交通燈 lights.green.on() #綠燈亮 while True: sleep(10) lights.green.off() #綠燈滅 lights.amber.on() #黃燈亮 sleep(1) lights.amber.off() #黃燈滅 lights.red.on() #紅燈亮 sleep(10) lights.amber.on() #黃燈亮 sleep(1) lights.green.on() #綠燈亮 lights.amber.off() #黃燈滅 lights.red.off() #紅燈滅
另外;
from gpiozero import TrafficLights from time import sleep from signal import pause lights = TrafficLights(2, 3, 4) def traffic_light_sequence(): while True: yield (0, 0, 1) # green sleep(10) yield (0, 1, 0) # amber sleep(1) yield (1, 0, 0) # red sleep(10) yield (1, 1, 0) # red+amber sleep(1) lights.source = traffic_light_sequence() pause()
使用LED組合:
from gpiozero import LED from time import sleep red = LED(2) amber = LED(3) green = LED(4) green.on() amber.off() red.off() while True: sleep(10) green.off() amber.on() sleep(1) amber.off() red.on() sleep(10) amber.on() sleep(1) green.on() amber.off() red.off()
2.12. Push button stop motion:
每按一次按鈕,使用相機模塊拍攝一張照片:
from gpiozero import Button from picamera import PiCamera button = Button(2) camera = PiCamera() camera.start_preview() frame = 1 while True: button.wait_for_press() camera.capture('/home/pi/frame%03d.jpg' % frame) frame += 1
有關完整資源,請參閱 Push Button Stop Motion 。
2.13. Reaction Game(反應遊戲):
當你看到燈亮起時,第一個按下按鈕的人就贏了!
from gpiozero import Button, LED from time import sleep import random #導入隨機庫 led = LED(17) player_1 = Button(2) player_2 = Button(3) time = random.uniform(5, 10) #隨機產生5到10之間的數 sleep(time) led.on() #燈亮 while True: if player_1.is_pressed: print("Player 1 wins!") break if player_2.is_pressed: print("Player 2 wins!") break led.off() #燈滅
有關完整資源,請參閱 Quick Reaction Game。
2.14. GPIO Music Box(GPIO音樂盒):
每個按鈕會發出不同的聲音!
from gpiozero import Button import pygame.mixer from pygame.mixer import Sound from signal import pause pygame.mixer.init() button_sounds = { Button(2): Sound("samples/drum_tom_mid_hard.wav"), Button(3): Sound("samples/drum_cymbal_open.wav"), } for button, sound in button_sounds.items(): button.when_pressed = sound.play pause()
有關完整資源,請參閱 GPIO Music Box。
2.15. All on when pressed(所有打開時按下):
按下按鈕時,蜂鳴器和全部指示燈亮起。
FishDish:
from gpiozero import FishDish from signal import pause fish = FishDish() fish.button.when_pressed = fish.on fish.button.when_released = fish.off pause()
Ryanteck TrafficHat:
from gpiozero import TrafficHat from signal import pause th = TrafficHat() th.button.when_pressed = th.on th.button.when_released = th.off pause()
使用LED,蜂鳴器和按鈕組合:
from gpiozero import LED, Buzzer, Button from signal import pause button = Button(2) buzzer = Buzzer(3) red = LED(4) amber = LED(5) green = LED(6) things = [red, amber, green, buzzer] def things_on(): for thing in things: thing.on() def things_off(): for thing in things: thing.off() button.when_pressed = things_on button.when_released = things_off pause()
2.16. Full color LED(全綵LED):
使用RGBLED產生色彩:
from gpiozero import RGBLED from time import sleep led = RGBLED(red=9, green=10, blue=11) led.red = 1 # full red sleep(1) led.red = 0.5 # half red sleep(1) led.color = (0, 1, 0) # full green sleep(1) led.color = (1, 0, 1) # magenta sleep(1) led.color = (1, 1, 0) # yellow sleep(1) led.color = (0, 1, 1) # cyan sleep(1) led.color = (1, 1, 1) # white sleep(1) led.color = (0, 0, 0) # off sleep(1) # slowly increase intensity of blue for n in range(100): led.blue = n/100 sleep(0.1)
2.17. Motion sensor(運動傳感器):
運動傳感器檢測到運動時點亮LED:
from gpiozero import MotionSensor, LED from signal import pause pir = MotionSensor(4) led = LED(16) pir.when_motion = led.on pir.when_no_motion = led.off pause()
2.18. Light sensor(光敏傳感器):
須要有個光敏傳感器,能夠檢測有光和黑暗:
from gpiozero import LightSensor sensor = LightSensor(18) while True: sensor.wait_for_light() print("It's light! :)") sensor.wait_for_dark() print("It's dark :(")
當光線改變時執行一個函數:
from gpiozero import LightSensor, LED from signal import pause sensor = LightSensor(18) led = LED(16) sensor.when_dark = led.on sensor.when_light = led.off pause()
或者根據檢測到的光線強弱改變PWMLED的亮度:
from gpiozero import LightSensor, PWMLED from signal import pause sensor = LightSensor(18) led = PWMLED(16) led.source = sensor.values pause()
2.19. Distance sensor(距離傳感器):
注意:在上圖中,能夠省略從傳感器通向麪包板的導線; 只需將傳感器直接插入邊緣的麪包板中。
讓DistanceSensor能夠檢測到最近的物體的距離:
from gpiozero import DistanceSensor from time import sleep sensor = DistanceSensor(23, 24) while True: print('Distance to nearest object is', sensor.distance, 'm') sleep(1)
當某物接近傳感器時執行一個函數:
from gpiozero import DistanceSensor, LED from signal import pause sensor = DistanceSensor(23, 24, max_distance=1, threshold_distance=0.2) led = LED(16) sensor.when_in_range = led.on sensor.when_out_of_range = led.off pause()
2.20. Motors(電機):
向前和向後旋轉電機:
from gpiozero import Motor from time import sleep motor = Motor(forward=4, backward=14) while True: motor.forward() sleep(5) motor.backward() sleep(5)
2.21. Robot(機器人)
讓機器人在一個大體正方形的區域中四處走動:
from gpiozero import Robot from time import sleep robot = Robot(left=(4, 14), right=(17, 18)) for i in range(4): robot.forward() sleep(10) robot.right() sleep(1)
製做一個帶有距離傳感器的機器人,當側得距離小於20釐米時,機器人就會轉彎:
from gpiozero import Robot, DistanceSensor from signal import pause sensor = DistanceSensor(23, 24, max_distance=1, threshold_distance=0.2) robot = Robot(left=(4, 14), right=(17, 18)) sensor.when_in_range = robot.backward sensor.when_out_of_range = robot.stop pause()
2.22. Button controlled robot(使用按鈕控制機器人)
使用四個按鈕做爲機器人的前進/後退/左/右控制鍵:
from gpiozero import Robot, Button from signal import pause robot = Robot(left=(4, 14), right=(17, 18)) left = Button(26) right = Button(16) fw = Button(21) bw = Button(20) fw.when_pressed = robot.forward fw.when_released = robot.stop left.when_pressed = robot.left left.when_released = robot.stop right.when_pressed = robot.right right.when_released = robot.stop bw.when_pressed = robot.backward bw.when_released = robot.stop pause()
2.23. Keyboard controlled robot(使用鍵盤控制機器人)
使用上/下/左/右鍵來控制機器人:
import curses from gpiozero import Robot robot = Robot(left=(4, 14), right=(17, 18))
actions = { curses.KEY_UP: robot.forward, curses.KEY_DOWN: robot.backward, curses.KEY_LEFT: robot.left, curses.KEY_RIGHT: robot.right, } def main(window): next_key = None while True: curses.halfdelay(1) if next_key is None: key = window.getch() else: key = next_key next_key = None if key != -1: # KEY DOWN curses.halfdelay(3) action = actions.get(key) if action is not None: action() next_key = key while next_key == key: next_key = window.getch() # KEY UP robot.stop() curses.wrapper(main)
注意:此方法使用的是標準curses模塊。 此模須要在Python的終端中運行才能正常工做,所以此方法在IDLE等環境中不起做用。
若是你更喜歡在IDLE下工做的版本,則如下方法應該足夠:
from gpiozero import Robot from evdev import InputDevice, list_devices, ecodes robot = Robot(left=(4, 14), right=(17, 18)) # Get the list of available input devices devices = [InputDevice(device) for device in list_devices()]
# Filter out everything that's not a keyboard. Keyboards are defined as any # device which has keys, and which specifically has keys 1..31 (roughly Esc, # the numeric keys, the first row of QWERTY plus a few more) and which does # *not* have key 0 (reserved) must_have = {i for i in range(1, 32)} must_not_have = {0} devices = [ dev for dev in devices for keys in (set(dev.capabilities().get(ecodes.EV_KEY, [])),) if must_have.issubset(keys) and must_not_have.isdisjoint(keys) ] # Pick the first keyboard keyboard = devices[0] keypress_actions = { ecodes.KEY_UP: robot.forward, ecodes.KEY_DOWN: robot.backward, ecodes.KEY_LEFT: robot.left, ecodes.KEY_RIGHT: robot.right, } for event in keyboard.read_loop(): if event.type == ecodes.EV_KEY and event.code in keypress_actions: if event.value == 1: # key down keypress_actions[event.code]() if event.value == 0: # key up robot.stop()
注意:此方法使用第三方evdev模塊。 首先使用sudo pip3 install evdev安裝此庫。 請注意,evdev僅適用於本地輸入設備; 這個方法不適用於SSH。
2.24. Motion sensor robot(運動傳感器機器人)
檢測到運動時讓機器人向前行駛:
from gpiozero import Robot, MotionSensor from signal import pause robot = Robot(left=(4, 14), right=(17, 18)) pir = MotionSensor(5) pir.when_motion = robot.forward pir.when_no_motion = robot.stop pause()
或者:
from gpiozero import Robot, MotionSensor from signal import pause robot = Robot(left=(4, 14), right=(17, 18)) pir = MotionSensor(5) robot.source = zip(pir.values, pir.values) pause()
2.25. Potentiometer(電位器)
連續打印鏈接到MCP3008模數轉換器的電位計值(0到1之間的值):
from gpiozero import MCP3008 pot = MCP3008(channel=0) while True: print(pot.value)
使用PWM在LED條形圖上顯示電位計的值,以表示狀態不會「填滿」LED:
from gpiozero import LEDBarGraph, MCP3008 from signal import pause graph = LEDBarGraph(5, 6, 13, 19, 26, pwm=True) pot = MCP3008(channel=0) graph.source = pot.values pause()
2.26. Measure temperature with an ADC(使用ADC測量溫度)
將TMP36溫度傳感器鏈接到MCP3008模數轉換器的第一個引腳:
from gpiozero import MCP3008 from time import sleep def convert_temp(gen): for value in gen: yield (value * 3.3 - 0.5) * 100 adc = MCP3008(channel=0) for temp in convert_temp(adc.values): print('The temperature is', temp, 'C') sleep(1)
2.27. Full color LED controlled by 3 potentiometers(由3個電位器控制全綵LED)
鏈接三個電位器(紅色,綠色和藍色)並使用它們的每一個值來產生LED的顏色:
from gpiozero import RGBLED, MCP3008 led = RGBLED(red=2, green=3, blue=4) red_pot = MCP3008(channel=0) green_pot = MCP3008(channel=1) blue_pot = MCP3008(channel=2) while True: led.red = red_pot.value led.green = green_pot.value led.blue = blue_pot.value
或者,如下示例產生相同的效果,但使用的是source屬性而不是while循環:
from gpiozero import RGBLED, MCP3008 from signal import pause led = RGBLED(2, 3, 4) red_pot = MCP3008(0) green_pot = MCP3008(1) blue_pot = MCP3008(2) led.source = zip(red_pot.values, green_pot.values, blue_pot.values) pause()
注意:上面的示例須要Python 3的環境。在Python 2中,zip()不支持延遲評估,所以腳本將掛起。
2.28. Timed heat lamp(定時加熱燈)
若是你有寵物(例如烏龜)須要天天開啓必定時間的加熱燈,您能夠使用Energenie Pi-mote遠程控制燈,TimeOfDay類來控制時間:
from gpiozero import Energenie, TimeOfDay from datetime import time from signal import pause lamp = Energenie(1) daytime = TimeOfDay(time(8), time(20)) lamp.source = daytime.values lamp.source_delay = 60 pause()
2.29. Internet connection status indicator(Internet鏈接狀態指示燈)
你能夠使用一對綠色和紅色LED展現你的互聯網鏈接是否正常工做。 只需使用PingServer類來肯定是否ping通google.com。 若是成功,綠色LED點亮,若是不成功,紅色LED點亮:
from gpiozero import LED, PingServer from gpiozero.tools import negated from signal import pause green = LED(17) red = LED(18) google = PingServer('google.com') green.source = google.values green.source_delay = 60 red.source = negated(green.values) pause()
2.30. CPU Temperature Bar Graph(CPU溫度條形圖)
你能夠使用內置的CPUTemperature類讀取Raspberry Pi本身的CPU溫度,並在LED的「條形圖」上顯示:、
from gpiozero import LEDBarGraph, CPUTemperature from signal import pause cpu = CPUTemperature(min_temp=50, max_temp=90) leds = LEDBarGraph(2, 3, 4, 5, 6, 7, 8, pwm=True) leds.source = cpu.values pause()
2.31. More recipes(更多方法)
繼續: