Site icon AranaCorp

Program your Raspberry Pi with C/C++

4.3
(33)

Ressources for Raspberry PI are generally written for Python but, as a micro computer, other languages can be used. If you know C/C++ ( If you come from the Arduino world, for instance) and don’t want to bother learning another computing language, it is possible to program Raspberry Pi using C/C++. In this tutorial we will see how to run C++ on Raspberry Pi and how to program your Raspberry Pi as an Arduino.

Material

Geany

Raspbian is delivered with Geany which is a text editor that can be used to write and execute a Python code.

Copy the following code:

#include <iostream>
using namespace std;

int main(int argc, char **argv)
{
  cout<<"Hello World" << endl;
	
	return 0;
}

C++ program must be compiled before being executed. In the menu “Build” select “Build”, or press F9 directly, to compile the code. Then, in “Build” select “Execute”, or press F5, to run the code.

The phrase “Hello World” should be displayed in the terminal of the Raspberry PI.

Program your Raspberry Pi like an Arduino

Install WiringPi

To control the I/O of the Raspberry Pi like the ones of the microcontroller Arduino you can use the library wiringPi.h.

In a terminal, check that the library is installed by typing:

gpio -v
gpio readall

If an error occurs, update your Raspbian installation with the commands:

sudo apt-get update
sudo apt-get upgrade

Then copy the GIT repository:

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

And compile the library:

cd ~/wiringPi
./build

WiringPi.h Wiring

The library WiringPi uses the GPIO numeration:

You can find the pinout by typing:

gpio readall

Base code to light a  LED with Raspberry Pi

Once the library installed, you can write a program using the same keywords as the Arduino in addition to the main() function and the basic includes.

#include <iostream>
#include <wiringPi.h>
using namespace std;

int ledPin = 29;  //Correspond à la pin 40

void setup(){

	pinMode(ledPin,OUTPUT);
	cout<<"Hello World" << endl;
}

void loop(){
	digitalWrite(ledPin,HIGH);
	delay(100);
	digitalWrite(ledPin,LOW);
	delay(100);

	cout<<"Blink the LED" << endl;
}

int main(void)//(int argc, char **argv)
{
	if(wiringPiSetup()<0){
		cout<<"setup wiring pi failed"<<endl;
		return 1;
	}
	setup();
	while(1){
		loop();
	}
	
	return 0;
}

To compile the C++ program using the wiringPi library with Geany, in the Build>Set Build Commands, in the case corresponding to Build Command, type : g++ -Wall -o “%e” “%f” -lwiringPi. You can then compile the code using the “Build” button and run it correctly using key F5.

Warning: Arduino libraries , otherwise specified, are not supposed to be compatible with Raspberry Pi. You may have to write your own library.

Sources

How useful was this post?

Click on a star to rate it!

Average rating 4.3 / 5. Vote count: 33

No votes so far! Be the first to rate this post.

Exit mobile version