[Logo for The C Shore Landing Page]
The C Shore

Blinking an LED

Table of Contents

Blinking an LED

With the help of the time library and a little loop, you can make the LED flash.

  • Create a new file by clicking New.

  • Save the new file by clicking Save. Save the file as gpio_led.py.

  • Enter the following code to get started:

      from gpiozero import LED
      from time import sleep
    
      led = LED(17)
    
      while True:
          led.on()
          sleep(1)
          led.off()
          sleep(1)
  • Save the file and run the code with by clicking on Run.

  • The LED should be flashing on and off. To exit the program click Stop.


Time Library: Functions vs. Methods

You may have noticed above that unlike the LED class from gpiozero that we use sleep from from the time library without instantiating an object.

That is because sleep is a regular function rather than a method. That is because a method is a function designed to work on objects of a class, while regular functions don’t require an object in order to do what they are supposed to do. Some languages don’t have objects at all, and only have variables and functions.

Loops

As you watched the LED you may have noticed that it continues to turn on and off until you click Stop. That is because the sequence of turning the led on, pausing (sleep), then off and pausing is inside a while loop. A while loop surrounds a group of statements that are to be executed for as long as the ‘condition’ of the while loop is ‘True’. In this the condition is ‘True’, and since True is always True, the while loop’s condition is always ‘True’, so the loop runs forever.

The gpiozero library’s LED class has a blink() method, so instead of the above you can do:

while True:
    led.blink()
  • Try adding some parameters to blink to make it blink faster or slower:

    • led.blink(2, 2) - 2 seconds on, 2 seconds off
    • led.blink(0.5, 0.5) - half a second on, half a second off
    • led.blink(0.1, 0.2) - one tenth of a second on, one fifth of a second off

    blink’s first two (optional) parameters are on_time and off_time: they both default to 1 second.


Your task

Change the flash speeds / on / off times.

Bonus task

Flash the LED in a sequence of your choice.