[ Raspberry Pi C ++] Our First LED (Controlling GPIO Output)

For this demonstration we will use an LED and have it blink. This post will not present anything new programming wise, rather it will get you familiar with connecting the GPIO pins to something physical.

Previous Post: Compiling, Linking & Using WiringPi

Next Post: Reading Input With Push Buttons

Connecting the GPIO Pins

The connection is rather simple, all we require is one wire going from an I/O Pin to the negative (-) end of the LED, and another wire from the positive (+) leg of the LED to the ground (GND) pin on the Pi.

If you would like to test that your LED is working before this point, instead of connecting to the GPIO pin, connect it to the 5V pin and your LED should illuminate. 

The following image demonstrates the setup with colour co-ordinated wires.

GPIO connection of single LED and GPIO pins
GPIO Connection of a single LED for the Raspberry Pi

As shown above, the green wire is connected to the negative connection of the LED (A.K.A the Cathode). This green wire is also plugged into GPIO pin number 3. This can become quite confusing as it is known as GPIO2 in the header table but the physical pin number is 3. These references matter in whatever way your code initialises wiringPi. Luckily, by default, wiringPi uses the pin numbers.

Finally, the positive leg of the LED (A.K.A the Anode) is connected to the ground pin to ensure a complete circuit.

Writing the Code

Now that we have the connection setup, we need to write the code to make the LED blink. In the previous tutorial we already looked at writing output to the GPIO pins. We will expand on this with a little additional Linux C++ code to delay the on/off state of the pin to make it blink.

#include <stdio.h>
#include <wiringPi.h>

#include <unistd.h> // Required for Sleep();

int main(int argc, char** argv)
    // Intialize the wiringPi Library

    // LED is connected on pin 3. Ensure
    // this pin is set to be an Output.
    pinMode(3, OUTPUT);

    // Ensure the LED is ON initialitial
    int state = HIGH;

    for(int i = 0; i < 10; i++)
        // Turn on or off depending on state
        digitalWrite(3, state);

        // Toggle to HIGH/LOW output
        state = (state == HIGH) ? LOW : HIGH;

        // Wait 1 second

    // Ensure we turn LED off
    digitalWrite(3, LOW);
    // Exit program
    return 0;
Blinking LED in C++

As this is a very straight forward example, each line in the code is commented accordingly.

Please refer to previous posts on how to compile the code and run it on the Raspberry Pi:

Once your circuit is complete and code compiled, run the program and watch the LED blink 10 times!

All code for these tutorials can be found here over at Github

Previous Post: Compiling, Linking & Using WiringPi

Next Post: Reading Input With Push Buttons