View project on Hackaday View project on GitHub

Hack Clock

A hackable alarm clock, built for experimentation and learning

Lesson Five: Adding Buttons to Push

Up to now the only way for us to interact with our clock has been through its web page and IDE. What if we aren't near our computers? Let's add a button on our Hack Clock so it can respond to us pressing it.

Before we keep going you need a button wired up to your Raspberry Pi, as detailed in the Creating Buttons and Switches section of the hardware instructions. We will be programming your clock to respond to pressing your clock's button down.

Eventually we will want this button to display the temperature outside, but before we do that let's write a simple test that will cause your display to show only zeros for a while. First up: we will write a function that zero's out your display. Let's name it "switchWeatherStations" since it will eventually show the weather. Have it turn off all the indicators and show zeros for the numbers:

# Blank the display def switchWeatherStations(): # Clear the display display.setColon(False) display.setEvening(False) display.setHours(0) display.setMinutes(0)

This would work - but it would quickly go back to showing the clock that updates every second. Let's make the clock pause for about three seconds by adding the Clock's "waitAbout(seconds)" function:

# Blink the display def switchWeatherStations(): # Clear the display display.setColon(False) display.setEvening(False) display.setHours(0) display.setMinutes(0) # Wait for about three seconds clock.waitAbout(3)

Now let's construct a new button by adding:

# What to do when you press a button Button(24)

Then we can tell our newly constructed button to call our function when pressed:

# What to do when you press a button Button(24).whenPressed(switchWeatherStations)

Let's save our work now. Once your new code is finished saving, when you press the button it should zero-out the display. If your button does not work, there is an even simpler test you can load to see if the problem is with the code or with the wires connecting the button. Go to the "Restore" page and load the "Using switches and buttons" example. That should dim and then brighten your display when a button is pressed. If that code doesn't work correctly, check with the person who put your Raspberry Pi together and have them check the button connected to the clock.

Nicely done! Now that the button works, let's get it to show the current temperature outside!