Blink a LED…or three!

One of the most illuminating little programs for the little ones is blinking a LED using the Raspberry Pi. The code is short, and the effect is dramatic. At least, it was when my 4 year old saw it!

The basic tutorial has been excellently written up here so there is no reason to repeat it here, except do NOT use the code from that site. There is a new library that makes it lot more simple, and intuitive, called gpiozero.

So, once you have the connections in place by following the instructions at the link above, this is the code you need to get it all going.

from gpiozero import LED
from time import sleep
led = LED(17)
while True:
    led.on()
    sleep(1)
    led.off()
    sleep(1)

That’s it. Run it and you should see it all blink away. This is also an excellent program to introduce the concept of object-oriented programming (oooh!) if your student happens to be slightly older. The LED is a physical object he can see and touch. And look, he can control it using the ‘led object’ in the code.

Finally, there are two simple things you can do to make this project more interesting:

Add more LEDs to the circuit! To do so, you will need to go back to the old electrical concept of series and parallel circuits…and make sure you connect the LEDs in parallel (I tried to connect them in series and it did not work…you can try for yourself too!). It work when connected in parallel because each LED gets the full 3V it deserves!

More colorful, right! :) Here it is, in technicolor.

The other thing you can do is to reduce the delay between the on/off states to 0.1 seconds or so, so that the LED blinks “sooper-fast”.

Happy blinking!