[ Raspberry Pi C ++] GPIO Access : Compiling, Linking & Using WiringPi

Previous Post: Using CMake

Next Post: Our First LED


To allow us access to the GPIO pins of the Raspberry Pi in C++ code, we will use a library known as “WiringPi”. What is nice about this library is that the functions we call are similar to those found in the usual Python examples. This should hopefully make it easier for those coming from Python programming on the Raspberry Pi.

As stated in my overview of C++, third party code usually comes in the form of a shared/static library which you link into your projects code. This is the case for WiringPi!

To acquire the use of a third party library, you normally get it in the form of precompiled binaries or downloading and compiling the source code yourself. What “precompiled binaries” mean, is that someone else has compiled the source code on their Pi/machine and distributed the .a/.so (static/shared library) file via a download medium. Precompiled binaries are usually the go-to way of using libraries on Windows machines. In this example however, we will be download the WiringPi source code and compile it ourselves.

Compiling WiringPi

The first thing you want to do is download the WiringPi source code. To retrieve the latest working copy of Wiring Pi, we will use git to clone the repository. If you are unsure if git is installed, you can run the following:

> sudo apt-get install git

Once git is installed, clone the repository by entering the following

> git clone git://git.drogon.net/wiringPi

After a few seconds git will have finished downloading. If you list the contents of the current directory (“ls” command) you will notice a folder named “wiringPi”. Simply change into this directory.

> cd wiringPi

If you list the contents of this directory, there will be a lot of files. The one that we are most interested in is the “build” script. Upon running this script, the compilation of the library will begin and its binaries and header files will be automatically installed into the appropriate /usr/local folders on our system.

> ./build

You should see the words “all done.” at the end of the build process once the binaries are compiled and installed.

Linking WiringPi

When linking a third party library into your C++ project, you usually have to tell the compiler where to find the libraries header and binary files. Thankfully, the build script executed in the compilation process installed these files into our /usr/local/include and /usr/local/lib folders. What is special about these folders is that they are on the system PATH variable, this means that compilers will look for files here by default!

Although we don’t have to tell the compiler where to look, we still have to tell it what to link. Luckily, this is only a one liner with CMake! I have commented each command and highlighted the line which links the wiringPi library. Here is the contents of the complete CMake file (notice I have changed the executable and project name)

# Minimum CMake version required to generate
# our build system
cmake_minimum_required(VERSION 3.0)

# Name of our Project
project(MyProject)

# add_executable creates an executable with
# The given name.
add_executable(MyEXE main.cpp)

# Make sure the executable links to the wiringPi lib
target_link_libraries(MyEXE wiringPi)
CMakeLists.txt

And finally, the code to run to see if the build system will link, compile and run our code:

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

int main(int argc, char** argv)
{
    wiringPiSetup();

    printf("wiringPi is working!\n");

    return 0;
}
main.cpp

In the above code, we simply include the wiringPi’s declared functions using the include statement and we are calling the wiringPiSetup function.

To generate the make files, make sure you have a subdirectory called build and make it the working direcotry

> mkdir Build && cd Build

Genreate the makefiles using CMake

> cmake ..

Compile the code

> make

If all goes well, you should be able to execute the program via its executable name and see the line “wiringPi is working!” appear in your terminal.

> ./MyEXE

If you see this, then you are ready to get started with programming in C++ for the Raspberry Pi!

Using WiringPi

Now that we have our program successfully linking and compiling WiringPi, we can now look at preparing the GPIO pins for use in our projects.

If you have come across some of the Python GPIO examples for the Raspberry Pi, the usual procedure is to:

  1. Initialise the GPIO Library
  2. Setup the I/O mode on each GPIO pin you intend to use
  3. Set/Read the pins state dependant on the mode you initiated it as (i.e. input / output)

Luckily, WiringPi is no different! And we’ve already seen from the code above how we initialise the GPIO library.

Just as an example of the functions we will be using in future posts, here is some code (commented on each line) which will set the output & read input from the GPIO pins.

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

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

    // Set the I/O state of the given pins
    pinMode(0, OUTPUT);
    pinMode(1, INPUT);

    // Turn pin 0 on then off
    digitalWrite(0, HIGH);
    digitalWrite(0, LOW);

    // Read input from pin 1
    int status = digitalRead(1);
    printf("Pin Input = %d\n", status);

    // Exit program
    return 0;
}
main.cpp

If you copy the above into your main.cpp file from earlier, and recompile the program you should see the line “pin input = 0” when executing. The status will be 0 until there is an input going into the pin… which we will look at when I get to push buttons 🙂

As a quick overall reminder, the full steps to generate your makefiles and compile your code is as follows (don’t execute the contents in brackets):

> cd Build (If not already in Build directory)
> cmake .. (If you have not yet generated makefile / added new files) 
> make     
> ./MyEXE

In the next post I will cover how to setup and make an LED flash using C++. If you want to give this a shot in the meantime though… Use the appropriate GPIO header table for your Pi and setup a GPIO pin in output mode to light up an LED.


Previous Post: Using CMake

Next Post: Our First LED

[ Raspberry Pi C ++] Using CMake

Previous Post: Setting Up The Compiler

Next Post: Compiling and Linking WiringPi for GPIO Access


In a previous post I talked about setting up a compiler on the Raspberry Pi and using g++ on the command line. This is all well and good as a small example with one file, but when you (rightly so) have your code broken up into many files, compiling them via the command line is no longer viable.

To get around this problem, programmers using GCC would create files known as “makefiles”.

Makefiles

Makefiles are GCCs way of passing to the compiler what source files need to be compiled and what they should be compiled into. A downside to using makefiles is that the syntax for them can get extremely cryptic and hard to read/understand when your code base grows.

When you start creating makefiles, you are creating what is known as a “build system” for your project. The more code files you have to manage, the more fundamental your build system becomes.

Different platforms/compilers have different ways of managing build systems for C++ projects. For example, the GCC default is with makefiles whereas Windows uses its own Visual Studio project solution files to manage build types. Technically, there are Windows ports of GCC compilers included in software such as MinGW or Cygwin but this isn’t the norm with regards to Windows programming.

This means that if you want to compile your code on multiple platforms you will have to create and maintain multiple build systems for your project.

For these reasons, programmers tend to look elsewhere for managing their build systems. One such tool is CMake

CMake

Note: I just want to make it clear here that CMake does not compile your code! CMake is one level higher than a native build system; infact, it abstracts the underlying build system completely with it’s own syntax and using what it calls “Generators“.

For example, you create your CMake files (described later) as you would your makefiles / Visual Studio files, but you will use a CMake generator to generate your build system files which can range from Makefiles to Visual Studio and Xcode projects. You will then use this generated build system to compile your code. Here is a list of CMake generators readily available.

It’s best to show the process with an example.

CMake Example on Raspberry Pi C ++

Installing CMake

Installing CMake on your Raspberry Pi is made easy by using the apt package manager.

First thing you want to do is SSH into your Pi and at the terminal/command line enter the following

> sudo apt-get install cmake

After a few seconds you should be able to enter the “cmake” command in the terminal and you will see a list of generators available.

Using CMake

For CMake to work, there should be a file named “CMakeLists.txt” in the root directory of your C++ project. In this example, I will have one CMakeLists.txt file and one Hello.cpp file from the previous tutorial.

Your folder structure should look like so:

- Root Folder/
| - CMakeLists.txt
| - Hello.cpp

To create the files enter the following command

> touch <filename.ext>

The contents for each file is as follows (notice each CMake command has a comment describing what it is doing)

#include <stdio.h>

int main(int argc, char** argv)
{
        printf("Hello, World!\n");
        return 0;
}
Hello.cpp
# Minimum CMake version required to generate
# our build system
cmake_minimum_required(VERSION 3.0)

# Name of our Project
project(hello)

# add_executable creates an executable with
# The given name. In our case it is "Hello"
# Source files are given as parameters. In our
# Case we only have one source file Hello.cpp
add_executable(Hello Hello.cpp)
CMakeLists.txt

Generating Our Makefiles

Now that we have our CMake file setup with our single source file Hello.cpp, we next need to generate the build system files. CMake will generate quite a lot of files and folders, so it is best not to run the CMake command in the project root directory. Instead we will create a sub folder called “Build” and run the generation in here.

> mkdir Build && cd Build

This will make the directory called “Build” and also change into the directory. This is how your folder structure should look now:

- Root Folder/ 
| - CMakeLists.txt 
| - Hello.cpp
| - Build/

To run the CMake Generator we need to use the “cmake” command and tell it where the root CMakeLists.txt file is. As we are in a sub directory we will use the parent directory alias “..”. If no generator is specified it will default to the platforms native build system (in the Pi’s case, this will be GCC makefiles)

> cmake ..

Once complete you can list the contents of the directory (using the “ls” command) and notice there is now a “MakeFile” present!

Compiling the Code

This bit is easy now that CMake has generated our MakeFile for us!

Simply enter the following into the terminal (make sure you are still in the Build directory)

> make

Provided you copied the code as is above, you should see the line “Built target Hello”. To execute the application enter the following:

./Hello

You should see the line “Hello, World!”


Previous Post: Setting Up The Compiler

Next Post: Compiling and Linking WiringPi for GPIO Access