金沙澳门官网基本方法,高级方法

作者: 网络编程  发布:2019-12-18

学习目录:山抛子派学习之路-GPIO Zero

官方网址地址:

环境:UbuntuMeta-16.04

树莓派:3代B型

以下情势身体力行了GPIO Zero库的部分效能。 供给注意的是怀有办法都以在 Python 3 的情景下编写制定的。方法恐怕在 Python 2 并没有用 !

3.1. LEDBoard

你能够循环LEDBoard的对象,LEDBoard的目的为LED集结:

from gpiozero import LEDBoard
from time import sleep

leds = LEDBoard(5, 6, 13, 19, 26)

for led in leds:
    led.on()
    sleep(1)
    led.off()

 LEDBoard同样支撑索引。 这象征能够利用 leds [i] 访问各样LED对象,当中 i 是从0到LED集结的数据:

from gpiozero import LEDBoard
from time import sleep

leds = LEDBoard(2, 3, 4, 5, 6, 7, 8, 9)

leds[0].on()  # first led on
sleep(1)
leds[7].on()  # last led on
sleep(1)
leds[-1].off()  # last led off
sleep(1)

 那也代表你可以应用切成丝来做客LED的子集:

from gpiozero import LEDBoard
from time import sleep

leds = LEDBoard(2, 3, 4, 5, 6, 7, 8, 9)

for led in leds[3:]:  # leds 3 and onward
    led.on()
sleep(1)
leds.off()

for led in leds[:2]:  # leds 0 and 1
    led.on()
sleep(1)
leds.off()

for led in leds[::2]:  # even leds (0, 2, 4...)
    led.on()
sleep(1)
leds.off()

for led in leds[1::2]:  # odd leds (1, 3, 5...)
    led.on()
sleep(1)
leds.off()

 LEDBoard对象能够在构造时命名其LED对象。 那代表可以透过名称访谈各种LED:

from gpiozero import LEDBoard
from time import sleep

leds = LEDBoard(red=2, green=3, blue=4)

leds.red.on()
sleep(1)
leds.green.on()
sleep(1)
leds.blue.on()
sleep(1)

 LEDBoard对象也得以嵌套在别的LEDBoard对象中:

from gpiozero import LEDBoard
from time import sleep

leds = LEDBoard(red=LEDBoard(top=2, bottom=3), green=LEDBoard(top=4, bottom=5))

leds.red.on() ## both reds on
sleep(1)
leds.green.on()  # both greens on
sleep(1)
leds.off()  # all off
sleep(1)
leds.red.top.on()  # top red on
sleep(1)
leds.green.bottom.on()  # bottom green on
sleep(1)

3.2. Who’s home indicator

行使多组绿 - 红LED灯对,你可以透过哪些可以成功ping通的IP地址来决断什么人家的互联网状态。 须要注意的是,那是即使每一个人的移动电话在家庭路由器上都有一个封存的IP地址。

from gpiozero import PingServer, LEDBoard
from gpiozero.tools import negated
from signal import pause

status = LEDBoard(
    mum=LEDBoard(red=14, green=15),
    dad=LEDBoard(red=17, green=18),
    alice=LEDBoard(red=21, green=22)
)

statuses = {
    PingServer('192.168.1.5'): status.mum,
    PingServer('192.168.1.6'): status.dad,
    PingServer('192.168.1.7'): status.alice,
}

for server, leds in statuses.items():
    leds.green.source = server.values
    leds.green.source_delay = 60
    leds.red.source = negated(leds.green.values)

pause()

 或者,使用STATUS Zero board:

from gpiozero import PingServer, StatusZero
from gpiozero.tools import negated
from signal import pause

status = StatusZero('mum', 'dad', 'alice')

statuses = {
    PingServer('192.168.1.5'): status.mum,
    PingServer('192.168.1.6'): status.dad,
    PingServer('192.168.1.7'): status.alice,
}

for server, leds in statuses.items():
    leds.green.source = server.values
    leds.green.source_delay = 60
    leds.red.source = negated(leds.green.values)

pause()

3.3. Travis build LED indicator(使用Travis构建LED指示灯)

行使LED组合呈现Travis创设的情状。 绿灯表示测量检验正在通过,红灯表示构建已破坏:

from travispy import TravisPy
from gpiozero import LED
from gpiozero.tools import negated
from time import sleep
from signal import pause

def build_passed(repo):
    t = TravisPy()
    r = t.repo(repo)
    while True:
        yield r.last_build_state == 'passed'

red = LED(12)
green = LED(16)

green.source = build_passed('RPi-Distro/python-gpiozero')
green.source_delay = 60 * 5  # check every 5 minutes
red.source = negated(green.values)

pause()

在意:那几个办法供给travispy。 使用sudo pip3 install travispy安装。

3.4. Button controlled robot(按键调控机器人)

而外轻易方法中的示例之外,你还足以利用八个按键内定机器人方向,并累计第四个开关来挨门挨户让他们运维,如Bee-Bot或Turtle robot。

from gpiozero import Button, Robot
from time import sleep
from signal import pause

robot = Robot((17, 18), (22, 23))

left = Button(2)
right = Button(3)
forward = Button(4)
backward = Button(5)
go = Button(6)

instructions = []

def add_instruction(btn):
    instructions.append({
        left:     (-1, 1),
        right:    (1, -1),
        forward:  (1, 1),
        backward: (-1, -1),
    }[btn])

def do_instructions():
    instructions.append((0, 0))
    robot.source_delay = 0.5
    robot.source = instructions
    sleep(robot.source_delay * len(instructions))
    del instructions[:]

go.when_pressed = do_instructions
for button in (left, right, forward, backward):
    button.when_pressed = add_instruction

pause()

3.5. 罗布ot controlled by 2 potentiometers(由2个电位器调整机器人)

应用七个电位计来决定机器人的左右电机速度:

from gpiozero import Robot, MCP3008
from signal import pause

robot = Robot(left=(4, 14), right=(17, 18))

left = MCP3008(0)
right = MCP3008(1)

robot.source = zip(left.values, right.values)

pause()

静心:上边的亲自过问须要在 Python 3 意况中运营。在Python 第22中学,zip()不援助延迟申报,由此脚本将挂起。

要包含反方向,请将电位计值从 0-1扩充到 -1-1:

from gpiozero import Robot, MCP3008
from gpiozero.tools import scaled
from signal import pause

robot = Robot(left=(4, 14), right=(17, 18))

left = MCP3008(0)
right = MCP3008(1)

robot.source = zip(scaled(left.values, -1, 1), scaled(right.values, -1, 1))

pause()

3.6. BlueDot LED

BlueDot是叁个Python应用程序,它同意你轻便地将蓝牙( Bluetooth® 卡塔尔(英语:State of Qatar)控件加多到你的 Raspberry Pi 项目中。

运用BlueDot应用程控LED的大约示例:

from bluedot import BlueDot
from gpiozero import LED

bd = BlueDot()
led = LED(17)

while True:
    bd.wait_for_press()
    led.on()
    bd.wait_for_release()
    led.off()

只顾:此方式必要bluedot和相关的Android应用程序。 有关设置表达,请参阅BlueDot文书档案。

 3.7. BlueDot robot(BlueDot机器人)

你能够创造三个Bluetooth调控的机器人,当按下该按键时它迈进挪动并在自由时停下:

from bluedot import BlueDot
from gpiozero import Robot
from signal import pause

bd = BlueDot()
robot = Robot(left=(4, 14), right=(17, 18))

def move(pos):
    if pos.top:
        robot.forward(pos.distance)
    elif pos.bottom:
        robot.backward(pos.distance)
    elif pos.left:
        robot.left(pos.distance)
    elif pos.right:
        robot.right(pos.distance)

bd.when_pressed = move
bd.when_moved = move
bd.when_released = robot.stop

pause() 

抑或越来越尖端的例证,包含调整机器人的速度和可信的可行性:

from gpiozero import Robot
from bluedot import BlueDot
from signal import pause

def pos_to_values(x, y):
    left = y if x > 0 else y   x
    right = y if x < 0 else y - x
    return (clamped(left), clamped(right))

def clamped(v):
    return max(-1, min(1, v))

def drive():
    while True:
        if bd.is_pressed:
            x, y = bd.position.x, bd.position.y
            yield pos_to_values(x, y)
        else:
            yield (0, 0)

robot = Robot(left=(4, 14), right=(17, 18))
bd = BlueDot()

robot.source = drive()

pause()

3.8. Controlling the Pi’s own LEDs(控制 Pi 自己的LED组)

在 Pi 的某个型号(特别是型号A ,B 和2B)上,能够决定 Pi 的功率和移动LED组。 那对于测量检验GPIO作用格外常有用,无需一而再三番五次本身的LED组(也很有用,因为电源和移动的LED是“已知优秀”)。

先是,你须要禁止使用内置LED组的常用触发器。 那能够经过以下命令在尖峰完结:

$ echo none | sudo tee /sys/class/leds/led0/trigger
$ echo gpio | sudo tee /sys/class/leds/led1/trigger

现今你能够运用 gpiozero 调控LED组,如下所示:

from gpiozero import LED
from signal import pause

power = LED(35) # /sys/class/leds/led1
activity = LED(47) # /sys/class/leds/led0

activity.blink()
power.blink()
pause()

要将LED组苏醒到健康情状,你能够重新启航Pi或运维以下命令:

$ echo mmc0 | sudo tee /sys/class/leds/led0/trigger
$ echo input | sudo tee /sys/class/leds/led1/trigger

注意:

在Pi Zero上,你可以动用此方调控移动的LED组,但从没单身的电源LED可供调整(还值得注意的是移动的LED组处于低电平状态有效,因此在创设筑组织调的LED组时设置active_high = False)。

在原始Pi 1(型号A或B)上,能够动用GPIO16垄断移动的LED组(在如上所述禁用其触发后),但电源的LED是通过硬接线达成的。

在Pi 3B上,LED组由GPIO增加器调节,该扩充器不可能从gpiozero(还未)采访。

 

上学目录:龙船泡派学习之路-GPIO Zero

官方网站地址:

环境:UbuntuMeta-16.04

树莓派:3代B型

2、基本方法(Basic Recipes)

上面演示了GPIO Zero库的部分职能,注意的是这个措施都以在python3下编写制定的,在python2下也许有用也说不许未有用!

2.1 导入GPIO Zero

行使GPIO Zero库有三种办法

2.1.1 单独导入GPIO Zero库的某些类

导入 GPIO Zero 的 Button :

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 编号

该库使用布罗兹com(BCM)引脚编号作为GPIO引脚,实际不是情理(BOAENVISIOND)编号。 与RPi.GPIO库区别,那是不行配置的。

金沙澳门官网 1

2.3 按键三个LED

金沙澳门官网 2

 不断的开垦和关闭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 出席一个开关

按键的连接如下图

金沙澳门官网 3

 检查是否按下了按键:

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灯

金沙澳门官网 4

按下开关时张开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(交通灯)

金沙澳门官网 5

一个交通灯系统。

使用像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/framed.jpg' % frame)
    frame  = 1

 有关总体财富,请参阅 Push Button Stop Motion 。

2.13. Reaction Game(反应游戏):

 金沙澳门官网 6

当您看来灯亮起时,第一个按下开关的人就赢了!

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):

 金沙澳门官网 7

使用ENVISIONGBLED发生色彩:

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(运动传感器):

金沙澳门官网 8

移步传感器检验到移动时点亮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(光敏传感器):

 金沙澳门官网 9

亟需有个光敏传感器,能够检查实验有光和天灰:

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(间隔传感器):

金沙澳门官网 10

只顾:在上海体育场地中,能够简简单单从传感器通向面包板的导线; 只需将传感器直接插入边缘的面包板中。

让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(电机):

金沙澳门官网 11

上前和向后旋转电机:

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(电位器)

 金沙澳门官网 12

接二连三打字与印刷连接纳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测温)

将TDVD6温度传感器连接到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 第22中学,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(越多措施)

继续:

  • Advanced Recipes
  • Remote GPIO Recipes

本文由金沙澳门官网发布于网络编程,转载请注明出处:金沙澳门官网基本方法,高级方法

关键词: 金沙澳门官网

上一篇:基本方法,树莓派官网学习记录
下一篇:没有了