Conditionals & Detecting button presses

Now the class is moving onto buttons, they need to be able to use conditions in Python. These let a program do different things depending on what's happening.

Learning objectives

Students will learn:

Resources

Lesson Plan

Conditional Tree : 15 minutes

You'll need some room to play this physical game. Outside works well!

Stand the the conditionals so one is at the front, then the other 2 are behind in a v shape. The rest of the class line up and one by one they go through the ‘tree’. Their personal answer will direct them to the next conditional. If the answer is True; go left, and if False; right.

Tips

Setup the Pi : 5 minutes

Setup the Pi and get logged in.

Detect a button with Python : 10 minutes

Build the circuit : 10 minutes

Ask the students to identify pin 16 on the Pi (8 down on the right hand side). Ask the students to build the circuit shown in the handout.

Run the code : 10 minutes

Ask the students to test their prediction by running the code. Students will discover that the code only checks the button once. They'll have to hold the button before starting the program to ever see the message that the button is pressed.

Ask the students to modify the code, adding a loop so that the program is checking continuously if the button is pressed. If they are stuck as them to look at the loop in the flash.py or stopwatch.py examples. The cheat sheet also has a looping example.

Once the students have done added a loop, ask them to look at the little box in the bottom right corner of the screen that shows CPU usage. They'll see that when they run the program the CPU is working at 100%!

Extension Activity

They can reduce CPU usage by including a small delay in our loop. The smaller the delay the harder the Pi has to work. Ask the students to add a delay and experiment with delay times. If they forgot how to do a delay then they can check their flash.py code. Try different lengths of delay. Is there a problem with increasing the delay too much? If it's too big then they might miss a button press.

Example code

This code adds the loop to continuously check the button, and reduces CPU usage by using time.sleep() to add a small delay.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
import time

button_pin = 16

#set the pin to be high to start, low when pressed
GPIO.setup(button_pin,GPIO.IN, pull_up_down=GPIO.PUD_UP)

#check if the button is pressed
while True:
    if GPIO.input(button_pin) == False:
        print("button pressed")
    else:
        print("button not pressed")

    #small delay to reduce CPU usage
    time.sleep(0.1)

Pack away : 5 minutes

Pack away the Pi.

Homework

Outcome

All students:

Most students:

Some students: