Book Image

Raspberry Pi Projects for Kids (Second Edition)

By : Daniel Leonard Bates
Book Image

Raspberry Pi Projects for Kids (Second Edition)

By: Daniel Leonard Bates

Overview of this book

Table of Contents (14 chapters)

Complete code listing


The complete code listing section shows the complete program. This may be useful if you're not sure where the different code snippets should go, or if your program isn't working and you want to compare it to something that works:

import RPi.GPIO as GPIO
import random
import time

def preparepins():
    GPIO.setmode(GPIO.BCM)
    for pin in options.keys():
        GPIO.setup(pin, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)

def nexttarget():
    target = random.choice(options.keys())
    print options[target]
    return target

def buttonpressed():
    for pin in options.keys():
        if GPIO.input(pin) == GPIO.HIGH:
            return pin
    else:
        return None

def play(duration):
    preparepins()

    start = time.time()
    end = start + duration
    score = 0

    target = nexttarget()
    while time.time() < end:
        button = buttonpressed()
        if button == target:
            score = score + 1
            print "Correct!"
            target = nexttarget...