In this exercise, we will use Python to light up the LED in the circuit we built in the previous exercise.

You will be working with Python functions in this exercise. If you are not familiar with functions in Python, check out the Codecademy docs on functions.

In this next example, let’s say we have an LED circuit connected to GPIO24. We initialize the LED class in Python like so:

from gpiozero import LED led = LED(24)

The LED class contains a method that turns an LED on. This method is .on() and is called using the instance contained in led. You call this method by writing led.on(). This will set the state of the GPIO at pin 24 to HIGH.

from gpiozero import LED led = LED(24) led.on()

To turn the LED off, we set the state of GPIO24 to LOW using: led.off().

from gpiozero import LED led = LED(24) led.on() # Turn LED on led.off() # Turn LED off

If you run this piece of code, you will notice that nothing happens to your LED! That is because this code executes so fast, you won’t be able to see the LED turn on then off again.

To actually see the LED turn on and off we have to put a pause between the .on() and .off() methods.

We will import and use sleep to stall the execution of code. The syntax is:

from gpiozero import LED from time import sleep led = LED(24) led.on() # Turn LED on sleep(1) led.off() # Turn LED off sleep(1)



You will now be using an emulation of a Raspberry Pi when using gpiozero. Once you create an LED instance the emulation will take around 10 seconds to run and then exit. This is indicated by the spinning circle inside the Run button.

If the emulation disappears from the workspace, click the refresh button in the workspace browser window.

Click Run to start the emulation. Good luck lighting up your first LED with gpiozero!


With the LED connected to pin 23, create the appropriate instance of the LED class in Python and assign it to the variable led2.


Blink the LED on pin 23 by turning it on for two seconds and turning it off for two seconds.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?