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

Lighting an LED

Table of Contents

Lighting an LED

LEDs are delicate devices. If you put too much current through them they will pop (sometimes quite spectacularly). To limit the current going through the LED, you should always use a resistor in series with it.

Try connecting the long leg of an LED to the Pi’s 3V3 and the short leg to a GND pin. The resistor can be anything over about 50Ω.

The LED should light up. It will always be on, because it’s connected to a 3V3 pin, which is itself always on.


Now try moving it from 3V3 to GPIO pin 17:

The LED should now turn off, but now it’s on a GPIO pin, and can therefore be controlled by code.






Switching an LED on and off

GPIO Zero is a new Python library which provides a simple interface to everyday GPIO components. It comes installed by default in Raspbian.

  • Open Mu.

  • You can switch an LED on and off by typing commands directly into the REPL. Click on the REPL button in the menu bar.

  • First import the GPIO Zero library, and tell the Pi which GPIO pin you are using - in this case pin 17.

     In [1]: from gpiozero import LED
     In [2]: led = LED(17)

    Press Enter on the keyboard.

  • To make the LED switch on, type the following and press Enter:

     In [3]: led.on()
  • To make it switch off you can type:

     In [4]: led.off()
  • Your LED should switch on and then off again. But that’s not all you can do.


About the import statement

The line from gpiozero import LED tells Python to pull in code from the gpio library, which is code that has been written by someone else and packaged so that you can use it easily.

In this case we are importing the LED class from that library. A class is a combination of variables (assigned values) and methods (things you can do with objects created from the class). An class is abstract which means that it doesn’t do anything until you give it’s variables some value. When we do that we say we ‘instantiate’ (create an instance/example of) the class to create an object which is can actually ‘do’ things.

When we say led = LED(17) we are saying create an instance (object) of the LED class that has a value of 17. For the LED class that means that GPIO 17 is what the methods will act.

The led.on() applies the method on() to the object led (which in this case is means turn GPIO 17 on).

When we turn GPIO 17 on, it becomes a 3.3V power source and creates a circuit though the LED and resistor to ground.