The best tools to make your project dreams come true

Login or Signup
USD

1/16/2019 | By Maker.io Staff

How To Use GPIO on the Raspberry Pi with C++

So far, we have learned how to use GPIO on the Raspberry Pi using Python, but not every project for the Pi will be done with Python. What if we wanted to use C++? Here, we’ll learn how to access GPIO in C++.

BOM

  • Raspberry Pi 3 Model B WITH RASPBIAN
  • 3mm Red LED
  • 1K Resistor
  • 10K Resistor
  • Tactile switch
  • SchemeIt

    How To Use GPIO on the Raspberry Pi with C++

    https://www.digikey.com/schemeit/project/maker-io-c-flash-AV30N4O402VG

    Wiring Pi Library

    C++ is an advanced language that includes many features, such as classes, objects, references, function prototypes, vectors, and much more. As a result of its capabilities, C++ is used in most environments including operating systems, scientific environments, and even Raspberry Pi’s. However, there is a downside to C++; it makes simple tasks overcomplicated. For example, when using GPIO in Python, the user imports the GPIO library, creates some variables, configures the pins, and boom the GPIO begin to work. C++, however, is not as forgiving and relies on complex file streams, which can make GPIO a nightmare. Luckily, there is a library called “Wiring Pi” that makes interfacing with GPIO much easier and this library, by default, comes with Raspbian!

    Our Simple Example – A Blinking Light with Disable Switch Code

    Copy Code
    #include <iostream>		// Include all needed libraries here
    #include <wiringPi.h>
    
    using namespace std;		// No need to keep using “std”
    
    int main()
    {
    wiringPiSetup();			// Setup the library
    pinMode(0, OUTPUT);		// Configure GPIO0 as an output
    pinMode(1, INPUT);		// Configure GPIO1 as an input
    
    // Main program loop
    while(1)
    {
    	// Button is pressed if digitalRead returns 0
    	if(digitalRead(1) == 1)
    {	
    	// Toggle the LED
    	digitalWrite(0, !digitalRead(0));
    delay(500); 	// Delay 500ms
    }
    }
    	return 0;
    }

    Code Explained

    Before we go into how the code works, let’s see the different wiringPi instructions that our program uses. Interestingly, the creator of the wiringPi library has stuck to the Arduino scheme, meaning that if you have used an Arduino before then these functions should be familiar.

    Copy Code
    #include <wiringPi.h>
    wiringPiSetup();
    pinMode(pin number, input / output);
    digitalWrite(pin number, state);
    digitalRead(pin number);
    delay(time in ms);

     

    The first lines in our program import all the needed libraries, including iostream and wiringPi. iostream provides our program with a means to write messages to the console window so we can see what’s going on. Meanwhile, the wiringPi library allows us to use the GPIO. After the libraries have been imported, we also use the instruction “using namespace std” that removes the need to constantly call the std class when printing text to the console.

    Copy Code
    #include <iostream>		// Include all needed libraries here
    #include <wiringPi.h>
     
    using namespace std;		// No need to keep using “std”

     

    With the libraries included, we now enter the main function - the entry point into our program. This is the major difference between C++ and Python; since Python starts executing code from line one. Whereas C++ programs start running code found in the main function. In our main function, we start by calling the function “wiringPiSetup()” which initiates the wiringPi library and prepares the Pi for using the GPIO. It is at this point that we also configure our two pins; the light output and the switch input.

    Copy Code
    wiringPiSetup();			// Setup the library
    pinMode(0, OUTPUT);		// Configure GPIO0 as an output
    pinMode(1, INPUT);		// Configure GPIO1 as an input

     

    PIN NUMBERING IN WIRING PI

    Pin number in wiringPi is not straightforward because the author used a wiring numbering scheme that does not refer to either the GPIO number or pin number. Long story short, when the Pi was first released, there were 8 useable GPIO pins which were numbered 0 to 8, but later releases have now seen many more GPIO with their names and numbering changed.

    To find out which wiringPi number of the pin you want to use, view the table below:

    How To Use GPIO on the Raspberry Pi with C++ 

    Image courtesy of The Raspberry Pi Hobbyist

    With all the pins configured, we now execute the main function while the loop runs indefinitely. The first instruction executed is an “if” statement that determines if the button is pressed. If it is, then the LED is toggled and a delay of 500ms is executed, else the LED stays in its current state.

    Do you notice anything interesting about this piece of code? If you look more closely, you will notice that the toggling of the LED is done by doing a digitalRead on an OUTPUT! Is that possible? Yes, and it’s incredibly useful! A digitalRead on an output pin will return the status of the I/O pin, making it useful as a method for checking if the output has actually changed to the desired value. In this case, we NOTE the result (using the “!” character), which means that our output will have a value written to it that‘s the complete opposite to the current state.

     

    Copy Code
    // Main program loop
    while(1)
    {
    	// Button is pressed if digitalRead returns 0
    	if(digitalRead(1) == 1)
    {	
    		digitalWrite(0, !digitalRead(0));	// Toggle the LED
            delay(500); 				// Delay 500ms
    }
    }

    Compile, Build, and Run the Program

    If you try to build a C++ program using the wiringPi library, it will throw errors saying “undefined reference”. This is because, despite having the library installed, the GCC compiler needs to be told to link in the wiring library. It is this requirement for setting command build instructions that makes C++ a somewhat hideous language to use. To link the wiringPi library in Geany, navigate to Build > Set Build Commands and enter “-lwiringPi” into both the compile box and build box as shown below.

    How To Use GPIO on the Raspberry Pi with C++

    With the library linked, it’s time to test everything out. With your code open in Geany - and making sure you have it saved to a user accessible folder such as Documents - start by compiling the code by pressing F8 on the keyboard or by going to “Build > Compile”. The window on the bottom of the IDE should show the message “Compilation finished successfully” if everything goes to plan. Then press F9 to build your program or go to “Build > Build” and the same message should appear if it’s successful. The last step is press F5, which will run your program and the LED should begin to blink. To prevent the LED from blinking, press and hold the switch!