Input/Output

Road Lights


In [0]:
from gpiozero import LED
from time import sleep

with LED(14) as red, LED(15) as green, LED(18) as yellow:
    while True:
        green.off()
        yellow.off()
        red.on()
        sleep(1)
        yellow.on()
        sleep(1)
        red.off()
        yellow.off()
        green.on()
        sleep(1)
        yellow.on()
        sleep(1)

In [0]:
from gpiozero import LED
from time import sleep
from signal import pause

with LED(14) as red, LED(15) as green, LED(18) as yellow:
    red.blink()
    green.blink(on_time=0.5, off_time=0.4)
    yellow.blink(on_time=0.2, off_time=2)
    pause()

In [0]:
from gpiozero import PWMLED
from time import sleep
from signal import pause

with PWMLED(14) as red, PWMLED(15) as green, PWMLED(18) as yellow:
    green.blink()
    red.blink(fade_in_time=1, fade_out_time=1)
    yellow.blink(fade_in_time=5, fade_out_time=5)
    pause()

Button


In [0]:
from gpiozero import Button
import sys

with Button(23) as button1, Button(22) as button2:
    button1.wait_for_press()
    print("The button1 was pressed!")
    sys.stdout.flush()
    button2.wait_for_press()
    print("The button2 was pressed!")

Button LED


In [0]:
from gpiozero import Button
from gpiozero import LED
from signal import pause

with LED(14) as red, Button(23) as button:
    button.when_pressed = red.on
    button.when_released = red.off

    pause()

Game


In [0]:
from gpiozero import Button
from gpiozero import LED
from time import sleep
import random

p1_score = 0
p2_score = 0
    
with LED(14) as led, Button(23) as p1, Button(22) as p2:
    round = 0
    while round < 10:
        time = random.uniform(1, 5)
        sleep(time)
        led.on()
        if p1.is_pressed:
            p1_score +=1
        elif p2.is_pressed:
            p2_score += 1    
        sleep(1)
        led.off()
        round += 1
        
print "Player 1:", p1_score
print "Player 2:", p2_score

Photo


In [0]:
from gpiozero import Button
import picamera
import time


with picamera.PiCamera() as camera, Button(23) as trigger:
    camera.hflip = True
    camera.vflip = True
    camera.start_preview()
    time.sleep(2)
    trigger.wait_for_press()
    camera.capture('image.jpg')
    camera.stop_preview()

# preview
from IPython.display import Image
Image(filename='image.jpg')

In [0]: