Ryanteck Traffic HAT - Blinking LED

Ryanteck Traffic HAT - Blinking LED

Blinking an LED in python has become really easy due to the new GPIO Zero library. There's a few different ways.

Lets begin by just turning the amber LED on. Open up your favourite python editor and type in the following to turn it on.

from gpiozero import LED

 

amber = LED(23)

 

amber.on()

And then try "amber.off()" to turn it off.

We can make the LED now blink by adding the following code at the top

from time import sleep

And as the body

while True:

    amber.on()

    time.sleep(1)

    amber.off()

    time.sleep(1)

This will then turn the LED off and on with a 1 second interval.

Congratulations you're now blinking a LED!

  • But wait, there's more!*

Instead a fancy feature of GPIO Zero is auto blinking which can be done using the following command.

amber.blink(1,1,None,False)

This will make the LED blink forever with a 1 second interval and pause the program.

We can change the False to True (or remove the ",False") section to make it so the rest of the program would continue.

You can change "None" to be a number which is how many times it would blink, Replacing "None" with 10 would make it blink just 10 times.

Finally you can change the two beginning numbers to set the intervals, using "1,2" would make the LED turn on for one second and then off for 2.

Leave a comment

All comments are moderated before being published.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.