beanz Magazine

Build an Electronic Sorting Hat

A fun way to learn basic electronics and coding with Python but minus the old rotting hat.

What will you need for this project?

  • Any model of Raspberry Pi
  • The latest Raspbian operating system
  • 6 x Male to female dupont connectors
  • 1 x Male to male dupont connector
  • 1 each of Red, Green, Yellow and Blue LEDs
  • 4 x 220 Ohm resistors (or 330 Ohm, the LEDs will just be a little dimmer)
  • 1 x Pushbutton / momentary switch
  • A breadboard with + and – rails

All of the code for this project can be found at https://github.com/lesp/GPIO-Zero-Sorting-Hat/archive/master.zip

Introduction

The wonderful world of witchcraft and wizardry was opened up to the world thanks to JK Rowling’s series of Harry Potter novels. One thing that children always want to know is “Which house would the Sorting Hat sort me into?” Well wonder no more aspiring witches and wizards, we shall make our own electronic Sorting Hat using a Raspberry Pi, some cheap electronic components and a little Python code.

We shall be covering the following concepts

  • Loops
    To control the main part of the code
  • Selection
    Conditional test based on answer to a question
  • Random Selection
    Selecting a random item from a list
  • Storing data in a list
    Using two lists to store messages and the houses
  • User interaction
    Asking the user to play the game by pressing a button

Building the Circuit

Let’s start with our push button.

The push button, sometimes called an momentary switch is a button that closes an electrical circuit when it is pushed. This means that the circuit is “normally open” until the button is pressed, and then it is closed.

The button sits over the central channel that is cut into the breadboard and is pressed firmly into the holes, creating an electrical connection. The button has two pins on either side. On one side of the breadboard connect the male to male connector in the same line as one of the legs of the button, and connect it to the – rail of the breadboard. This means that the leg of the button is now grounded. The other leg next to that we have just connected is linked to GPIO22 of our Raspberry Pi using a female to male connector.

Hogwarts House LED Color GPIO
Gryffindor Red 2
Slytherin Green 3
Hufflepuff Yellow 27
Ravenclaw Blue 17

Now grab another female to male connector and place the male end into the – rail of the breadboard, the same rail that we have connected our button to. Then connect the female end to any of the Raspberry Pi GPIO Ground pins. Now our button is fully connected to the Raspberry Pi.

Our LEDs, short for Light Emitting Diodes which are components that light up when current is supplied in the correct direction, have two legs. The longer leg is called the Anode and it receives current from the Raspberry Pi GPIO.

The shorter leg, the Cathode, is connected to our Ground rail (-) via the resistor. Resistors are used to reduce the current that flows in the LED circuit, if there is too much then the LED will shine very bright, and then fizzle out. The resistors reduces the current and ensure our LED has a long life.

For each color we connect the long leg to the corresponding GPIO pin.

Refer to the table diagram above to see where each color physically connects to the Raspberry Pi.

When the wiring is complete, power up your Raspberry Pi and go to the Raspbian / Pixel desktop.

Coding the Sorting Hat

We’ll start coding using the Python 3 editor, which can be found in the Programming section of the main menu.

The editor is called IDLE and it will open to a screen called “the shell”, here we can interact with Python in real time. But for this project we shall click on File >> New to open a new blank document. Once it is open, click on File >> Save and call the project “sorting.py”, then click Save / Ok. Remember to save your work often!

Our first few lines of Python are called “imports” and they import pre-written libraries of code into our project. For example we import a library called GPIO Zero, used to easily interact with the GPIO of the Raspberry Pi. From that library we import tools to work with Buttons (inputs) and LEDs (outputs). Then we import the choice function from the random library, this is used to randomly choose something from a list. Lastly we import the sleep function from the time library, this is used to pace the project, otherwise the computer will do things too quickly.

from gpiozero import Button, LED
from random import choice
from time import sleep

Now we need to tell GPIO Zero where our button, used to trigger the Sorting Hat, and the LEDs that represent our houses, are connected to the GPIO. We do this by creating variables which will store these positions for us to use later in the code.

button = Button(22)
gryffindor = LED(2)
slytherin = LED(3)
hufflepuff = LED(27)
ravenclaw = LED(17)

Our Sorting Hat needs phrases to tease the player, and these are stored in a list. A list is an object that can contain multiple entries, which are all stored in an index that starts at zero. This means that we can retrieve items from a list by stating the name of the list, and it’s position as a number. We also create a list for the various Hogwarts Houses.

phrases = [“Difficult, you are very difficult to sort”,”You are a hero, I know which house you belong to”,”I sense a darkness in your magic”,”When duty calls you will do your bit for the school”]
houses = [“Gryffindor”,”Slytherin”,”Hufflepuff”,”Ravenclaw”]

We then instruct the player to press the button to start the game.

print(“Press the button to learn which house you will be joining”)

Now we enter the main loop that will control our game. In Scratch a forever loop will run the code inside of it, forever. In Python this loop is called “while True” and it works in the same manner, any code inside the loop will run forever.

while True:

Now the code that follows is automatically indented by four spaces, to show that it belongs inside the while True loop. We instruct Python to wait for our Button to be pressed before moving onwards.

   button.wait_for_press()

Once the button has been pressed the code creates a variable called “message” and in there it stores a randomly chosen phrase from our phrases list. We also create a variable called “house” and in their store a randomly chosen house. Both of these variables are then printed to the Python Shell using a print function.

   message = choice(phrases)
    house = choice(houses)
    print(message, house)

So now we know which house we are in, but lets use the power of LEDs to flash the corresponding LED color. For this we use a conditional test. This test will use a series of “if and else if” tests to compare the value stored in the variable “house” against a series of hardcoded values.

Our first test checks to see if the variable “house” contains the word “Gryffindor”, if that is correct then the code that is indented under the test is run. In this case the LED we named “gryffindor” will blink (flash) with 0.2 seconds on and 0.2 off. The code will sleep for five seconds before turning off the gryffindor LED. Note that the code under the if test is indented by four spaces.

   if house == “Gryffindor”:
        gryffindor.blink(0.2,0.2)
        sleep(5)
        gryffindor.off()

We repeat this test three more times, covering all of the houses at Hogwarts. We use “elif” which is Python’s way of saying “else if”. These “elif” tests are activated if the first test is false. The tests are repeated, checking each house and flashing the correct LED.

   elif house == “Slytherin”:
        slytherin.blink(0.2,0.2)
        sleep(5)
        slytherin.off()
    elif house == “Hufflepuff”:
        hufflepuff.blink(0.2,0.2)
        sleep(5)
        hufflepuff.off()
    elif house == “Ravenclaw”:
        ravenclaw.blink(0.2,0.2)
        sleep(5)
        ravenclaw.off()

Our last line of code is outside of the if..elif conditional tests, so make sure that the four space indentation is removed, simply press Backspace to do this. Our last line is a sleep for 0.2 seconds, we do this to ensure that the Raspberry Pi is not overworked.

   sleep(0.2)

And that is all of the code for this project, make sure that you save the code!

Just in case you need it here is all of the code for this project.

from gpiozero import Button, LED
from random import choice
from time import sleep
button = Button(22)
gryffindor = LED(2)
slytherin = LED(3)
hufflepuff = LED(27)
ravenclaw = LED(17)
phrases = [“Difficult, you are very difficult to sort”,”You are a hero, I know which house you belong to”,”I sense a darkness in your magic”,”When duty calls you will do your bit for the school”]
houses = [“Gryffindor”,”Slytherin”,”Hufflepuff”,”Ravenclaw”]
print(“Press the button to learn which house you will be joining”)

while True:
    button.wait_for_press()
    message = choice(phrases)
    house = choice(houses)
    print(message, house)
    if house == “Gryffindor”:
        gryffindor.blink(0.2,0.2)
        sleep(5)
        gryffindor.off()
    elif house == “Slytherin”:
        slytherin.blink(0.2,0.2)
        sleep(5)
        slytherin.off()
    elif house == “Hufflepuff”:
        hufflepuff.blink(0.2,0.2)
        sleep(5)
        hufflepuff.off()
    elif house == “Ravenclaw”:
        ravenclaw.blink(0.2,0.2)
        sleep(5)
        ravenclaw.off()
    sleep(0.2)

Now run your code, click on Run >> Run Module to start the code and the Python Shell will leap forward ready for use. Press the pushbutton on your breadboard to start the game and marvel as the Sorting Hat chooses your house!

Congratulations you have made your own Electronic Sorting Hat.

During this project we learnt that

  • Breadboards are used to connect electronic components
  • LEDs are a form of output
  • Resistors are used to reduce the current and ensure our LEDs last a long time
  • There is a library called GPIO Zero that can be used to easily work the the GPIO
  • Lists can be used to store lots of information
  • Random selections can be made using the random library

How could we take this game further?

  • It would be rather fun to add a method to Tweet your house. You can learn more about this via this great resource https://www.raspberrypi.org/learning/getting-started-with-the-twitter-api/
  • Or you could add sound effects using Pygame’s audio mixer and a selection of magical audio files https://www.pygame.org/docs/ref/mixer.html

Learn More

Source Code

https://github.com/lesp/GPIO-Zero-Sorting-Hat/archive/master.zip


Also In The June 2017 Issue

Can we measure the time and steps required for things to happen?

This Canadian experiment used a robot to explore how people respond to robots and technology.

An amazing new book turns math problems into shapes and illustrations.

This pen and paper project helps organize ideas into stories with a finite state machine.

While you can't use soap and water on your code, you can keep your code as sparkly clean as any dish or silverware.

This project explores the basics of using Google's Static Map software to display your own maps.

Most people love cookies. But these cookies are the kind that make the internet possible.

Links from the bottom of all the June 2017 articles, collected in one place for you to print, share, or bookmark.

Interesting stories about computer science, software programming, and technology for June 2017.

Software languages don't magically appear. They're created by design. First in a series.