WiringPi Examples

Update: 14th May, 2013

wiringPi version 2 has been released and now has its own website (http://wiringpi.com/) to look after it. Most of the documentation on the projects site has been copied over to it the new site, but there may still be 1 or 2 pages that are still missing. I’d encourage you to use the new site if possible where there will be a forum and wiki (when I get time to implement them!)

Here are two small example programs, demonstrating the use of the WiringPi library. These programs are presen in the examples directory of the wiringPi distribution. Please see refer to the versions there for the current “best practices” for using wiringPi.

The first test program needs 8 LEDs wired to the 8 normal GPIO outputs – WiringPi pins 0 through 7. It also has a switch connected to WiringPi pin 8 shorting to ground when pushed. (That will normally read 1 when not pushed due to the on-board 1k8 pull-up resistor – ignore the 2k2 comment in the code, it’s 1k8!)

 * test1.c:
 *      Simple test program to test the wiringPi functions

#include <wiringPi.h>

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

// Simple sequencer data
//      Triplets of LED, On/Off and delay

uint8_t data [] =
            0, 1, 1,
            1, 1, 1,
  0, 0, 0,  2, 1, 1,
  1, 0, 0,  3, 1, 1,
  2, 0, 0,  4, 1, 1,
  3, 0, 0,  5, 1, 1,
  4, 0, 0,  6, 1, 1,
  5, 0, 0,  7, 1, 1,
  6, 0, 1,
  7, 0, 1,

  0, 0, 1,      // Extra delay

// Back again

            7, 1, 1,
            6, 1, 1,
  7, 0, 0,  5, 1, 1,
  6, 0, 0,  4, 1, 1,
  5, 0, 0,  3, 1, 1,
  4, 0, 0,  2, 1, 1,
  3, 0, 0,  1, 1, 1,
  2, 0, 0,  0, 1, 1,
  1, 0, 1,
  0, 0, 1,

  0, 0, 1,      // Extra delay

  9, 9, 9,      // End marker

} ;

int main (void)
  int pin ;
  int dataPtr ;
  int l, s, d ;

  printf ("Raspberry Pi wiringPi test program\n") ;

  if (wiringPiSetup () == -1)
    exit (1) ;

  for (pin = 0 ; pin < 8 ; ++pin)
    pinMode (pin, OUTPUT) ;

  pinMode (8, INPUT) ;  // Pin 8 SDA0 - Has on-board 2k2 pull-up resistor

  dataPtr = 0 ;

  for (;;)
    l = data [dataPtr++] ;      // LED
    s = data [dataPtr++] ;      // State
    d = data [dataPtr++] ;      // Duration (10ths)

    if ((l + s + d) == 27)
      dataPtr = 0 ;
      continue ;

    digitalWrite (l, s) ;

    if (digitalRead (8) == 0)   // Pressed as our switch shorts to ground
      delay (d * 10) ;  // Faster!
      delay (d * 100) ;

  return 0 ;

This 2nd test demonstrates the PWM function: (WiringPi Pin 1 connected to a standard LED via a 220Ω resistor)

 * test2.c:
 *      Simple test program to test the wiringPi functions
 *      PWM test

#include <wiringPi.h>

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

int main (void)
  int pin ;
  int l ;

  printf ("Raspberry Pi wiringPi PWM test program\n") ;

  if (wiringPiSetup () == -1)
    exit (1) ;

  for (pin = 0 ; pin < 8 ; ++pin)
    pinMode (pin, OUTPUT) ;
    digitalWrite (pin, LOW) ;

  pinMode (1, PWM_OUTPUT) ;

  for (;;)
    for (l = 0 ; l < 1024 ; ++l)
      pwmWrite (1, l) ;
      delay (1) ;

    for (l = 1023 ; l >= 0 ; --l)
      pwmWrite (1, l) ;
      delay (1) ;

  return 0 ;



WiringPi Examples — 146 Comments

  1. Looks good! Do you have any circuit diagrams for what you tested this code with?
    I am wary of running things straight off a board that would take months to replace :S

    • Not yet, but I have been testing with simple LEDs and switches so-far. A 330 ohm resistor in-series with an LED connected from GPIO to ground is sufficient. For switch input, then my Wiring pins 8 and 9 are connected to the I2C pins on the Pi’s GPIO connector and these have a built-in 1k8 resistor to +3.3v, so shorring them to ground is fine with a simple push-button switch.
      I’ll put up some photos soon of the breadboards I’m using with it, so check back in a day or 2!

  2. Hi. Very amature question, I have made an 8 LED test board to have a go with your example code, but I am unable to recompile the .c files that I create with cc. I am in the examples directory, but get “undefined reference to” for all of the wiringpi functions. Any advice?

    • If you’ve installed the wiringPi library, then you need to link it in, so for a simple single-file program you might compile it like this:

      cc -o program program.c -I/usr/local/include -L/usr/local/lib -lwiringPi


      • I’ve asked this question elsewhere. How do you get the library to be a permanent part of g++ libraries? I.e. I want to write the program from a text editor, and need not bother since it will be included in any case.
        I currently can use only bash as described above, and find it confusing to compile a program.

        btw: After the “program.c” I can only compile if that first “-l” is a capital “-L”. Is it your typo or my utter Noobness?

        • If you’ve done the make install in the wiringPi directoyr (check by ls /usr/local/include and ls /usr/local/lib – see if the wiringPi files are there), then the -l (lower case) specifies the library name, and the -L (upper case) specifies the location.

          So if you have a program called fun.c, then to compile it with wiringPi:

          cc -o fun -I/usr/local/include fun.c -L/usr/local/lib -lwiringPi

          The -I part will let you use #include in the source file, and the -l and -L flags will allow the library to be found and linked in.


          • It took me a while to figure out why I couldn’t install GPIO with the supplied Makefile. It seemed gertboard was missing in libwiringPi.a. Adding gertboard.o and -.c in the makefile in the wiringPi dir helped a bit. I finally succeeded by also adding wiringPiSPI in the makefile in that directory. Or did I overlook something?
            Next comes using your lib to capture pulses on a GPIO pin to create a one-bit logic analyser for protocolanalysis of a weather station. Anyway, nice lib, thanks for sharing!

          • I’m somewhat surprised at the compile failures. Was this from a GIT install?
            I test each release on a “clean” Pi with no other headers, etc. so I’m a little concerrend that you needed to add these files in to make it compile. Can you let me have more details. Email is ok if you like.



          • I am also having issues compiling the above examples.
            I have renamed my files to fit your examples and have cut and pasted your syntax directly into the console window.

            I’ve pasted in what I’m getting for an output. I used git, i noticed some things look different. in /usr/local/lib i have libwiringPi.a. In /usr/local/include i have my wiringPi.h header file. Any direction is appreciated at this point.

            below is the outputs.
            root@DevBoard:~/Desktop# cc -o program program.c -I/usr/local/include -L/usr/local/lib -lwiringPi
            cc: error: program.c: No such file or directory
            root@DevBoard:~/Desktop# cp test.c fun.c
            root@DevBoard:~/Desktop# cc -o fun -I/usr/local/include fun.c -L/usr/local/lib -lwiringPi
            fun.c:13:1: error: stray ‘\302’ in program
            This continues, but i didn’t want this message to be to large

          • The first error seems to be because there is no “program.c”. That’s the filename.

            And test.c – I’m assuming you’ve copied and pasted the files from the web page… I’m suspecting a stray character has gotten in there somewhere.

            If you did the git clone operation from your home directory, try this:

            cd wiringPi/examples
            cc -o test1 test1.c -lwiringPi

            you may want to look at the program you have – try

            less test.c

            to display it on-screen.


  3. Hello,
    is there a way to get the exact time (in useconds) for pin being HIGH like in that Arduino example:
    void loop()
    // Start Ranging
    digitalWrite(TRIGPIN, LOW);
    digitalWrite(TRIGPIN, HIGH);
    digitalWrite(TRIGPIN, LOW);
    // Compute distance
    float distance = pulseIn(ECHOPIN, HIGH);
    distance= distance/58;

    Thanks im advance!

    BTW Good job

    • Hi,

      One of the issues with the Pi (compared to Arduino, etc.) is that the Pi is running a multi-tasking operating system – ie. Linux! So what this means is that Linux can interrupt your program at any point to do something else (like service the LAN, USB, or handle someone typing on a keyboard for example). So trying to do software timing loops is not going to be very successfull – it will probably work most of the time, but every now and then you’ll get the wrong result, so it’s not something I’d like to rely on. You could run a little assembly routine that turns off interrupts while you are sampling the pin, however that’s really not a goot idea in Linux.

      Arguably the correct way to do this in the Pi might be to start a timer (hardware or software), then arrange to wait on an interrupt from the pin, then stop the timer, however even this may suffer from schedulling issues.

      On way to do this might be to still use the Arduino to do the jobs involving precise timings, then pass the data back to the Pi for more processing, storage, etc. however it does complicate things somewhat!


  4. Oh here is my current code i just want to increase the accuracy



    #define ECHOPIN 0
    #define TRIGPIN 1

    int main (void)
    struct timeval tv,tve;
    struct timezone tz;

    printf (“RasPi Distance with HC-SR04 \n”) ;

    if (wiringPiSetup () == -1)
    exit (1) ;

    pinMode (ECHOPIN, INPUT) ;
    pinMode (TRIGPIN, OUTPUT) ;

    digitalWrite (TRIGPIN,0) ; //LOW
    digitalWrite (TRIGPIN,1) ; //HIGH
    digitalWrite (TRIGPIN,0) ; //LOW
    for(;;) {
    if (digitalRead (ECHOPIN) == 1) {
    for(;;) {
    if (digitalRead (ECHOPIN) == 0) {

    float usec;
    usec = tve.tv_usec – tv.tv_usec;
    usec = usec/58; //Distance = ((Duration of high level)*(Sonic :340m/s))/2
    return 0 ;

    • Ah, I see what you’re doing now, and yes, I think that will be somewhat problematic on the Pi.

      Might be easier to use one of the LV-EZ range – e.g. LV-EZ4 which has serial as well as analogue output – then use the serial data. However that won’t help if you already have the HC-SR04 unit! (Which are also attractive as they’re about a tenth of the price of the LV units!)

      There is a trick or 2 you can do to improve accuracy though – one is to make many samples and throw away the ones that are wildly out of the range you think your doing to get. You might also just implement a software counting loop too, but you’d then need the calibrate it. Using a loop like this would avoid any system calls – and those are times when your program is likely to be de-schedulled – e.g. the first call to gettimeofday might cause a re-schedulle..

      It’s an intersting problem though – might even get one of these and have a play myself as they’re quite cheap!


  5. Thank you for your response!

    Maybe a solution is to rerun the code more than once and compare results.
    I’ll do some test and keep you posted.

    • Hi Peach,

      did u manage to test more?
      I might order some to play with too, and would be interesting to see your results 🙂

  6. I don’t know if it is a bug or what…

    I connected a BC548 to the PWM and then to a series of LEDs, and I’m doing this:

    gpio mode 1 pwm
    gpio pwm 1 135

    But the LEDs, at 134, turns off… at 135, turns at half, 136, turns full… and 190, offs… and the cyce continues until 1023. I thought it should be dim and get brighter until get to 1023… isnt it? feel free to email me if you want faster response. thanks!

    • Hi,
      I don’t think it’s a bug as it’s working fine for me and others. I’m wondering if you’re picking up the right pin? Pin 1 (in wiringPi) is BCM_GPIO_18

        • Not impossible, however, I’d start by making sure you can use that pin in ordinary digital mode first. So
          gpio mode 1 out
          gpio write 1 1
          gpio write 1 0
          and make sure the LED can be turned on and off, then try again:
          gpio mode 1 pwm
          gpio pwm 1 50
          gpio pwn 1 500
          etc. The range is 0-1023.

          • I did that 🙁 will make a video tonight to show it. Btw, I’m using the kernel from the guy that made the Dallas 1-wire interface patch. I don’t know if that affects.

  7. I’m using your library and I’m having a funny issue. When I set a pin to output and then test it with my multimeter, with the + on the gpio and the – on GND, I get -3v3.

    Am I missing something about the way the GPIO operate?

    • I’m sure you’ve checked… but are you sure the leads are plugged into your multimeter the right way round?


      • Indeed they correct, I also tested this with my breadboard and the ULN2003 (a darlington transistor array). I connected pin4 to positive and the common ground of the ULN2003 to ground and nothing happened. That’s when I measured and found this oddity. I then test between 3v3 and ground and 5v and ground and both of those measured correctly.

        • If it helps here’s the important lines of my program

          int lightLED = 4;

          pinMode (lightLED, OUTPUT) ;

          digitalWrite (lightLED, 0); //(0 volts LED off)

          digitalWrite (lightLED, 1); //(3v3 volts LED on)

        • I have no idea why, but when I accidentally reset the pi (I believe it happened when I testing my pins and touched a DNC and ground wire…ooops) after the reset the issue was gone. It now lights up exactly as it is supposed to and I feel a little like an idiot since I can’t reproduce the issue to prove it wasn’t user error >:(

          Anyways, thanks for the willingness to look in this 🙂

          • No problems, but I am wondering if it wasn’t some issue with your multimeter though! The Pi really doesn’t have the compoments to generate a negative voltage on the GPIO pins…

            And you’re not the first one to reboot a Pi by accidental GPIO pin shorting out…


          • It would be pretty hard to be an issue with my multimeter. It’s my work multimeter that get’s professionally calibrated twice a year and more than that, I could confirm the behavior by wiring the GPIO as ground and the ground as the positive terminal. Hopefully it will forever stay a strange little mystery and never happen again!

    • I have the same issue myself, and I can reproduce it quite reliably. This is my first attempt to use the GPIO on my RPi, but I have tinkered a little bit with microcontrollers and some analog circuits. I’m quite confident that I’m measuring -3v3 from pin0, as I also use the same VOM to measure +3v3 from a trusted PSU source. I’m using the gpio utility freshly built from your github to test. It’s v1.5. I own a relatively early rev 1 RPi board. My shipment was affected by the integrated magnetics ethernet jack manufacturing issue. After a reboot/powercycle, I execute the following commands:

      gpio mode 0 out
      gpio write 0 1

      I have header 11 connected to what I think should be a positive pin0 and header 6 connected as a ground. However, like I said, on pin0 I get -3v3. I’ve tested this with both Arch Linux ARM and the latest Raspian. Same negativity. Also, I have never shorted by board with a DNC header pin.

      It’s not a big issue for me. I can just hook up my IO circuit in reverse; and I don’t plan on doing much else with the GPIO pins. However, I thought it may be interesting to report the issue. I haven’t found this dicussion happening anywhere else anyway.


  8. Any chance to control addressable LED’s? ws2801 or LPD8806? I know how to send data with Arduino but I want to controll these with Pi.

    Let me know!


    • Hi,

      A quick look at the WS2801 datasheet suggests it’s fine. And using wiringPi, you can probably use more or less the same code to drive it too.

      the LPD8806 looks similar – both should be do-able with bit-banging 2 GPIO pins to clock the data into them.


    • Just had a closer look at the WS2801 data sheet (more because it might help me with a project I have later this year!)

      The critical thing appears to be that you DONT’T stop clocking the data out for more than 500uS – becuase when you do that, it causes the chips to then transfer the 24-bit data into the output latches…

      So you’ll need to make sure that the function that clocks the data out is running at a high priority with nothing else interrupting it. I think it should be possible – you might want to check the piHiPri function in wiringPi.


  9. Hello, i’m trying with the gpio command to use as others linux commands. Write 0 or 1 works, but i don’t know how to use the pwm option. I’ve connect a led to the 3.3v and to the gpio 18. Then: gpio mode 18 out / gpio -g pwm 18 500 … i don’t know, please help me.

    • that ought to work fine:

      gpio -g mode 18 pwm
      gpio -g pwm 18 512

      should set an LED to half brightness

      gpio -g pwm 18 1023

      is full brightness, and

      gpio -g pwm 18 0

      is off.

      Do make sure there is a resistor in-series with the LED – about 270 or 330 ohms is OK for most LEDs.


  10. WiringPi is great the way it does the Wiring/Arduino software. But It will be better if give the user interface for user control the board via mouse/display.

    • Well, wiringPi is just a library, so anyone can use it to write some sort of graphical front-end for it. I’ve written some stuff in my BASIC in the past using it, but it’s not quite ready for public consumption yet! If you’re a whizz with graphics programming on Linux then …. 😉


  11. Help.
    I’m saturated with bad information on using these GPIO pins.

    Can you PLEASE demonstrate, from beginning to end, how to make the test1.c program work? I don;t know why it wont work for me but I DID install wiringPi and have checked the directory /wiringPi/examples contains your C and obj files. Show us what to do with them!

    I really need a walk through of a single, working example. Possibly something with a single pin flashing a led?

    Thank you in advance

  12. i would love to have a simple 1 led 1 button tutorial to iam new to programming and already this is making no sense to me.

    • try this. 1 led, no button
      conect the led on pin 6 and pin12
      the program is:


      int main() {

      if (wiringPiSetupGpio () == -1)
      exit (1) ;

      pinMode (18, OUTPUT);
      digitalWrite (18, 1);

      return 0;

      save as test2.c

      sudo gcc -Wall -L/usr/local/include -L/usr/local/lib test2.c -lwiringPi -o test2

      sudo ./test2

  13. thanks gordon

    in the mean while i try to learn it mineself so if u heard about a guy blowing up his raspberry u know i faild lol.

    thanks for the effort gordon.

  14. Many many thanks to the codes and stuff….I succeed in running test2…started the c file with “sudo ./test2″…pressed ctrl+c to get back to normal command line in the terminal….but..the LED still kept on blinking….what is the command to stop the c file running??
    Sorry for the dumb question….

      • well….it kept on dimming and then brightening in cycles….(which i guess indicates the program is still running)…
        I was even horrified as I log out and return to the initial command screen (where you normally type startx)…the lights were still blinking….

  15. Gordon – seems there is some confusion caused by the typeface used here that doesn’t discriminate between ‘l’ (lower case ell) and ‘I’ (upper case eye) which may account for the compilation failures. Cut and paste works OK if you are running your Pi via SSH, but it’s confusing if you are just trying to type in the commands.

    sudo cc -o test2 test2.c -I/usr/local/include -L/usr/local/lib -lwiringPi
    ^ ^

  16. …seems that the spacing has been lost in my attempt to illustrate the problem; the first -I before /usr/ is uppercase eye, the second -l before wiringPi is lowercase ell.

  17. I’ve been using a logic analyzer to watch the output of test2 and something weird is happening. The duty cycle is changing, but so is the PWM period. I played around a bit with pwm, and noticed that this behavior is consistent. Is it possible that that pwmWrite is writing multiple registers?

    This is using the latest git master.

    • Well you can check the code 🙂

      However it’s also highly possible that the PWM hardware just doesn’t work as documented.

      Try adding a call to pwmSetMode (PWM_MODE_MS) ; in test2.c after the wiringPiSetup () call.


    • Hi,

      I don’t think it would be hard to do – but the back-end from th eweb page would be the clever part. If it were me, I’d be writing it in C, but I have experience of writing CGI applications in C – You might want to use php, perl, or python as the back end – even using bash with the gpio command would work.

      Making it pretty would be the hard part for me!

      So I’d start by looking at how to write CGI programs in whatever language you are most familiar with and take it from there.


      • thanks gordon! thanks for replying so quick! yup, i’ll look into CGI for C also, haha

  18. hi gordon finaly got wiringpi loaded on to my pi it may sound a funny question but how do i stop the test programs type sudo ./test1 and the lights on my gertboard start flashing great but how do i stop them typed quit and exit but they still flash away the only way i can stop them is to unplug my pi i must be doing something wrong

    • Oddly enough, you’re not the first person to notice this, although I’ve not seen it myself, so I think I’ll go back and have a look to see why this might be happening. It shouldn’t! When you hit control-c, that should kill the program….


      • Hi Gordon,

        I remember having the same experience when testing the PWM example file, even ctrl+Z won’t stop the lights. But after restarting Pi, everything was normal again =]=]=] hope that helps.

        By the way, thank you very much for the great lib. =]

  19. Hi Gordon, I am just starting out hooking up gadgets to my Pi and first out i thought i would try to connect a 433.92MHz transmitter and/or reciever or both if possible. These are cheap things i got off ebay, and at the moment i am unusure even what pins to connect them to on the Raspberry GPIO.
    My hope is to be able to control simple remote power switches and/or to recieve info from my 433.92MHz RF weather station, doorbell, alarm system etc. and when i have had enough fun with that and learned a bit more, evenually set up an automated system for my fish tank.

    The reciever has three pins, DATA, VCC and GND so i figured i could connect the VCC to PIN 1 (labled 3.3v in your GPIO layout) GND to ground on Pin 6 (0v), and Data to RxD on Pin 10 (just because it felt logical, but probably isn’t)

    The transmitter has four pins: VCC, GND and two data.

    Is this a doomed project from start or do you have any hints?

    With best regards from Sweden,

    • Assuming the module is designed to run at 3.3v, then I suspect there’s a good chance of it working.

      See this little program for a small example of getting data off the serial line:

      You’ll probably need to work out the baud rate – that’s assuming it is sending serial data and not some weird encoded signal…


  20. Hi Gordon and thank you for your quick reply!
    looking closer it seems the transmitter is made to run on 3V up to 24V, i guess that would affect the transmitting power, sadly the reciever is designed to use 5V (+0.5) so i guess im out of luck with these ( http://www.ebay.co.uk/itm/110932082507 ). Though i do have two more RPis on the way (the 512MB versions), i am not too keen on frying this one. Guess i am better off getting some tranciever that is better suited for the RPi or find something else as my first project. I’m just a bit excited and want to get started with something and this was something i had been hoping to get playing with for some time now.

    Much appreciated and thank you for your great work!

    All the best,

    • After a very quick look at it, I suspect a simple resistor divider to take the input to the Pi to 3.3v would suffice. They do look pretty simple though…

      I have had good experiences with XRF/URF kit though – if you can get it where you are – plugs directly into the USB port on the Pi..


  21. Yes i think they are about as simple as they come, but for that price i guess i shouldn’t expect much. I am still in the very beginning of this journey so i think I will shelf them for the moment along with the RF control project and start off with something simpler, like getting a LED to blink, to start with.
    Atleast I hope to be able to accomplish that and feel some satisfaction instead of frustration and giving up on it totally. 😀
    Many thanks for the pointers and help, keep the good work up!

    All the best,

  22. I am trying to use wiringPi via the Anjuta IDE.

    This is my test program:

    /* main.c */

    int main()
    return 0;

    When I build the project I get error message:
    main.c:7: undefined reference to `wiringPiSetupSys’.

    wiringPi.h is being found OK, so I guess that the linker is not finding the library file. I have tried adding ‘-L/usr/local/lib -lwiringPi’ in the linker flags line of project properties, without success.

    Does anyone know how to configure Anjuta to work with wiringPi please?



    • I’ve never used Anjuta before, so don’t really know much about how it links things in. It does seem odd that it can find the .h file, but not the library though.


      • In case anyone else struggles with this …
        For some reason, Anjuta fails to correctly transfer the linker flags from project properties to Makefile.am.
        To enable linking to the wiringPi library it was necessary to modify the Makefile.am entry:
        myprog_LDFLAGS =

        to read …
        myprog_LDFLAGS = \

        Thanks for a great library, Gordon.


        • That’ll be fixed real soon. It’s a “gotcha” when I tried to include both the dynamic and static libraries.


          • I have reported this as an Anjuta bug. Is the problem not with Anjuta, but with the way the library is installed?


  23. Hi Gordon – I’m a bit surprised at my speed test example (speed.c) results.

    The pass and average are in milliseconds and for average it also includes the # of iterations per second. Correct?

    What throws me is the /sys/class/gpio method result which I assumed (silly me) would be the slowest one. SLOW_COUNT being used for that test would also indicate that’s what we are expecting as well.

    My speed.c run:

    Raspberry Pi wiringPi speed test program
    Native wiringPi method: (10000000 iterations)
    Pass: 0: 713mS
    Pass: 1: 712mS
    Pass: 2: 714mS
    Average: 713mS: 14025245/sec
    Native GPIO method: (10000000 iterations)
    Pass: 0: 640mS
    Pass: 1: 639mS
    Pass: 2: 641mS
    Average: 640mS: 15625000/sec
    /sys/class/gpio method: ( 1000000 iterations)
    Pass: 0: 40mS
    Pass: 1: 41mS
    Pass: 2: 41mS
    Average: 40mS: 24590163/sec

    And for grins, set it to the same # of iterations:

    /sys/class/gpio method: (10000000 iterations)
    Pass: 0: 406mS
    Pass: 1: 409mS
    Pass: 2: 406mS
    Average: 407mS: 24570024/sec

    Is this right? I’m getting ~24Mhz on the /sys/class/gpio method vs. ~14-15Mhz on the others? It makes me think something isn’t right.

    I’m using raspbian wheezy on a rev 2 board and compiled wiringPi with “sudo ./build” and no other flags set.

    $ gpio -v
    gpio version: 1.5
    Copyright (c) 2012 Gordon Henderson
    This is free software with ABSOLUTELY NO WARRANTY.
    For details type: gpio -warranty

    This Raspberry Pi is a revision 2 board.

    • Well spotted, that man!

      There is a little “feature” there – one that was easily overlooked by me – essentially, before calling wiringPiSetupSys() the pins need to be exported …

      So edit speed.c and before the line that reads:

      if (wiringPiSetupSys () == -1)
      exit (1) ;

      Inser this line:

      system (“/usr/local/bin/gpio export 17 output”) ;

      then run it:

      /sys/class/gpio method: ( 1000000 iterations)
      Pass: 0: 2964mS
      Pass: 1: 2963mS
      Pass: 2: 2965mS
      Average: 2964mS: 337381/sec

      I must have had the pin exported outside the program when I was running and testing it myself. Note in my own book: Reboot Pi before doing tests before releasing a release!


  24. Ah! Eureka!

    I added it in the “Switch to SYS” mode section and viola.. we are now going mighty sloooow for that part.

    Now my dreams of a 20+Mhz GPIO read for a project of mine are dashed. 😛

    Now off RPi topic – if you can think of a way to get 8bit @40Mhz data stream captured through any reasonable means, let me know.

    • I’m fairly sure the hardware itself is limited to that ~20MHz figure – RAM is obviously much faster though. You could read the entire 32-bit GPIO register in one cycle though, so if your data is presented as a parallel stream of 8 bits at 5,000,000 a second then it might be possible, but not 8 bits 40,000,000 times a second..

      Good luck with whatever you end up doing!


  25. Hi Gordon

    I was looking at the okLed.c code (which works fine) but you refer to making it run in the background from boot up.

    My rc.local file is:-

    # Print the IP address
    _IP=$(hostname -I) || true
    if [ “$_IP” ]; then
    printf “My IP address is %s\n” “$_IP”

    exit 0

    if I want to add it in where do I put it to make it run in the background. The executable is still in the root@raspberrypi:/home/pi/wiringPi/examples# directory



    • I have:

      /home/gordon/wiringPi/examples/okLed &

      in my /etc/rc.local … It’s not a perfect location for it, but it works!

      What I/You should probably do is move the executable to /usr/local/bin/ and run it from there…


      • Thanks Gordon, That worked

        I assume the “&” at the end of a command makes anything run in the background

        There is soooo much I don’t know, and the more you show me, the more I realise there is still so much more I don’t know!!

        Thanks again


        • Yes it does!

          Try it from the normal command-line:

          sudo ./okLed &

          you’ll get back its process ID. (which you can use with the kill command to stop it running, or type ‘fg’ to bring it to the foregound, then control-c)

          It’s not technically the correct way to kick things off at boot time in the Debian/init scheme of things, however it’s good enough for now.


  26. Hi Gordon,

    thanks for the great library – I’ve just received my Raspberry Pi and plan to use it to build an aquarium monitor/control system – I used “git clone” to fetch the wiringPi library and then ./build to build and install it. I am able to build and run test1 and test2 using “make”. However when I try to build “wfi” iand some of the other examples get an error from the linker –

    pi@raspberrypi ~/wiringPi/examples $ make wfi
    [CC] wfi.c
    /usr/local/lib/libwiringPi.a(piThread.o): In function `piThreadCreate’:
    piThread.c:(.text+0x18): undefined reference to `pthread_create’
    collect2: ld returned 1 exit status
    make: *** [wfi] Error 1

    What did I miss?

    Note: I’m using Raspbian:
    Linux raspberrypi 3.1.9adafruit+ #10 PREEMPT Thu Aug 30 20:07:05 EDT 2012 armv6l GNU/Linux


    • Yes, a small issue has come back to bite me (and everyone) when I re-introduced the static libraries )-:

      If you modify the Makefile to add -lpthread to the LDLIBS line then it’ll be fine, and I’ll fix it in the next release.


  27. Good morning Gordon:
    First of all thanks for the great library. I have a problem because I have this code:


    int main(void)
    int setup = 0;
    setup = wiringPiSetup();
    if(setup != -1)
    { while(1)
    waitForInterrupt(7, -1);
    printf(“Caught interrupt\n”);

    I compile the code and i don’t have any problem
    gcc -o test main.c -lwiringPi

    Later I do:
    gpio edge 7 falling

    I execute the program and the program don’t receive nothing and I have this:

    I hope you can help me.

    • WordPress removes all the nice formatting, sadly, however..

      The main issue is that the interrupt handling code works entirely via the sysfs interface, so you need to call wiringPiSetupSys() first, and not the standard wiringPiSetup().

      make sure you go the gpio edge 7 falling before running your program.

      I am working on a much improved version though that’s easier to use and compatible with the standard wiringPiSetup mode, but that won’t be ready for a week or 2.


  28. Hi Gordon.
    I’ve got an Arduino Leonardo (clone) and was wondering if you knew whether it worked with this variant.
    I’m trying to just get an LED flashing.
    I know that the LED is wired up correctly because I can use an Arduino sketch to flash it to my heart’s content. But, when I run my script on the Pi, nothing happens.
    I hope you can give me a few pointers to debug the problem.

    Yours hopefully,


    Here’s my code:

    int main(void) {
    int greenLedPin = 5;

    printf (“Initialised\n”);

    if (wiringPiSetup() == -1)

    pinMode(greenLedPin, OUTPUT);

    for (;;) {
    digitalWrite(greenLedPin, 1);
    printf (“On\n”);
    digitalWrite(greenLedPin, 0);
    printf (“Off\n”);

    return 0;

    • Your program looks fine (other than wordpress re-formatting )-:

      First thing I’d check is that you have the right physical pin number. Pin 5 here is physically pin 18 on the header. See the diagram here to check: https://projects.drogon.net/raspberry-pi/wiringpi/pins/

      Looking down on the Pi with the Ethernet to the right, then its:

      o o o o o o o o o o o o o
      o o o o X o o o o o G o o

      X marks the spot, G is ground/0v


  29. Hi gordon,

    First of all thank you for this library this is going to help me a lot !

    Then, i’m new and not familiar with coding and develloping under Linux, so i’m learning a little more every day 🙂

    I have a little problem, when i use an IDE such as Code::blocks to run my program, it does work, but when i want to run it without compiling and executing through code:blocks, nothing happens.

    How can i fix this ?

    If you want my code : http://tinypaste.net/xXEF6hGm

    Thanks in advance ! 🙂

    • If you have that program saved as (e.g.) mycode.c, then the command:

      gcc -omycode mycode.c -lwiringPi

      will compile it, and to run:

      sudo ./mycode


      • Woah, thanks for the quick answer.

        I didn’t knew that i needed to run it from the terminal.
        Is there any way to make a clickable shortcut or something like that in order to run it easy from the desktop like any other program ?

        • Yea, but I don’t know how to. You’ll need to do some reading up for the window manager you’re using (probably lxde, but I use xfce and I don’t know how to do it under that either as I do almost everything from command-line…)


  30. Thanks Gordon for a fantastic job with wiringPi !

    Picked up my model B on my way out from work Friday and by Saturday eve I am bangin’ bits on a 2 color LED scavenged from a dead PC. BTW save those PC case LEDs, they have a little plug that fits the raspberry pi header, just snip one wire to add a resistor.

    What took me so long? First disabling the monitor timeout, linux noob stuff like learning GIT, finding the pinout (which way is UP as well as wiringPi numbering), sudo ./test1 instead of sudo test1, and trying to compile.

    Like a good plagiarist copied test1.c to mytest.c in examples and hacked away. Detailed messages at your site for folks having trouble compiling had me baffled. Finally I did

    make mytest
    sudo ./mytest

    any LO it works ! Is it really that easy to compile / make C++ to bang bits? Either I got lucky or youre a genius. I’m going to fridge right now to get you a beer. Since youre not here I might need to drink it for you.

    Project: vague notions of displaying household systems status on an unused HDMI of the main TV. Could become a web server, but right now just a terminal window with numbers and text, and LEDs to tell if raspberry pi has something interesting on that video channel.

    Anyway thanks a million for wiringPi, great work, if we are ever on the same side of the pond you can drink that beer yourself !

  31. Hi Gordon, love wiringpi, great work. Wondering if you can help. Playing around with wiringPi. If I run my program automatically from init.d pwm doesn’t work but normal digital out does. Tried moving it to rc.local but same result. Can you shed any light?


    • Struggling to think why that may be… Do make sure you use the full pathname to gpio – ie. /usr/local/bin/gpio as there is no environment setup.

      I may have to do some tests myself.


      • Hello, been playing around with a few more tests. Not really sure what I’m doing here tbh…

        I wasn’t using gpio in my original program, don’t think so anyway, it was something similar to pwm test2 above. It works fine if run from the command line but run as service(?) via an init.d start/stop script and pin1 pwm doesn’t seem to do anything.

        Now, the same program but using softpwm instead and it works fine (although a little jittery as you would expect)

        I then tried a bash script using the gpio utility, setting up pin1 as pwm. Worked from command line but not when run via init.d

        Back to my original program, run as service (& appended, running in background) and no pwm output. If then I run another similar program; to init, set pwm value and exit. pwm output from original (running in background) then appears.

        • I’ve made a new release of wiringPi – there appears to be a few issues for some, so if you can, run a

          git pull origin

          in your wiringPi directory, then another ./build and see how that goes.

          I have 3 Raspberry Pis to test this on, but they’re all running Raspbian with different hardware attached and so-far all the releases have worked fine for me, but I’m not sure about stuff running for others now..


  32. Hello

    I have problem with compile your library in Codeblocks. In terminal I must write:

    gcc -o blink blink.c -lwiringPi

    How implement it in Codeblocks compiler. Could you help me? I add screenshoot setting Codeblocks. Where must I change?


    • I’ve never used clodeblocks, sorry.

      I’d look for a setting that included an external library and add in -lwiringPi (or just wiringPi, whatever it needs)


      • ok, I will check it.

        Which software do you use?

        Could you recommend me some software with intellisense for programming C on RaspberryPi?

        • I use straightforward editor (vim) and Makefiles for all my C projects.

          Have done for over 30 years now. (Well, not with vim, but similar editors before it)


  33. Hello

    I use this example code:


    int main (void)
    printf (“Raspberry Pi blink\n”) ;

    if (wiringPiSetup () == -1)
    return 1 ;

    pinMode (0, OUTPUT) ; // aka BCM_GPIO pin 17

    for (;;)
    digitalWrite (0, 1) ; // On
    delay (500) ; // mS
    digitalWrite (0, 0) ; // Off
    delay (500) ;
    return 0 ;

    When I write in terminal:

    pi@raspberrypi ~ $ gcc -o prg prg.c -lwiringPi
    prg.c: In function ‘main’:
    prg.c:6:3: error: stray ‘\302’ in program
    prg.c:6:3: error: stray ‘\240’ in program
    prg.c:9:5: error: stray ‘\302’ in program
    prg.c:9:5: error: stray ‘\240’ in program
    prg.c:11:3: error: stray ‘\302’ in program
    prg.c:11:3: error: stray ‘\240’ in program
    prg.c:15:5: error: stray ‘\302’ in program
    prg.c:15:5: error: stray ‘\240’ in program
    prg.c:16:5: error: stray ‘\302’ in program
    prg.c:16:5: error: stray ‘\240’ in program
    prg.c:17:5: error: stray ‘\302’ in program
    prg.c:17:5: error: stray ‘\240’ in program
    prg.c:18:5: error: stray ‘\302’ in program
    prg.c:18:5: error: stray ‘\240’ in program
    prg.c:20:3: error: stray ‘\302’ in program
    prg.c:20:3: error: stray ‘\240’ in program
    pi@raspberrypi ~ $

    How can I fix this?

    • It looks like something has gone wrong in the download somewhere – or your editor has converted some characters? How did you copy blink.c into prg.c?

      (And what happens if you try the same compile command with blink.c?)

      My suspicion is that the double quotes have been turned into unicode 66’s and 99’s.


  34. Yes, I have copyied all to nano editor.

    When I write

    gcc -o prg prg.c

    I have the same problem.

    • I still think something is happening to the code when you copy it, and I’m fairly sure it’s to do with the double-quotes being changed into a different character set.

      I don’t know what to do about it though.


  35. Hi Gordon,

    I’ve been using the wiringPi library from my C code, and its all good. However I now need to link in some C++ modules and am having problems with “undefined references” when i try to link – for example, my C++ code includes “rpiGpio.h” and then does:

    if (gpioSetup() != OK) {
    blah blah;

    This works fine with cc, and it compiles with gcc, but the gcc linker says

    valve_utils.cpp:(.text+0x8): undefined reference to `gpioSetup()’

    I get the same error for all the other gpio functions in the library.

    I took a look at the rpiGpio.h include file, and have been banging on this for a couple of days, off and on, and can’t figure it out.

    Any idea why gcc thinks I’m referring to a new function? it must have something to do with the return value or the parameters but I can’t figure it out for the life of me…


    • Are you sure you’re using wiringPi?

      I ask, as wiringPi does not have a function called gpioSetup (it’s wiringPiSetup), nor does it have a file rpiGpio.h…


  36. I’m sorry – my confusion, of course. Turns out I’m using Alan Barr’s gpio library for gpio (https://github.com/alanbarr/RaspberryPi-GPIO), and wiringPi (wiringSerial) to access the serial port . I’ll see if I can figure out how to contact him for advice, or perhaps try to switch to wiringPi for the gpio stuff. Not sure how I ended up using both. libraries…


    • No wories… Looks easy to switch to wiringPi if you need to though, or just put the usual “C” wrappers round the function declarations in that code in the .h files. WiringPi has it already in.


  37. Total newb question here, but what is the purpose of writing low to pins 1 to 8 in the second example?


    • To be honest I don’t know. I suspect it’s probably left-over from some other little program I was working on at the time. You can safely ignore it.


  38. made a car with wiringPi. (* proud owner of a car with a user account *)

    somehow gpio0 and gpio3 aren’t coming loose. so i cant steer yet 😉 also the pwm for the motor is very quick and dirty programmed by myself.. i only could get pin 1 to work on pwm with the gpio tool… (though now i read your library examples and i see that there is something called softPwm that may work on more pins…)

  39. i now understand, i’ll try that… And maybe the gpio tool could complain some more about this. (it lets you enable any pin into pwm mode)… i still need to find out why my gpio0, and 3 (bcm 17 and 23?) are stuck. did i blow them? (nah.. i was careful all the way…) or could it have anything to do with other installed software?
    i hope this photo link works:

    Anyway. thanks a lot again for your good work!

    • It’s possible you’ve blown them – the only way to know is to test them! You can use the gpio command to test them individually – gpio -g mode 17 out ; gpio -g write 17 1 etc.


  40. Hi Gordon.

    Thank you very mucho for your work. It is a great work.

    I have a little problem. I’m using the wiringPiISR function to execute a piece of code when one of the pin receive 3,3 vols.

    Code works greats but what can I do to execute only one time until function don’t finish?

    I have created a volatile int variable that controls if subrutine is finished but don’t work.

    Here a litte piece of code…

    in main …
    if (wiringPiISR (BOTON1, INT_EDGE_FALLING, &Funcion) < 0)
    return 1;

    the function…

    void Funcion(void)
    if(Terminado==1) {

    If variable Terminado==1 then can execute subrutine but if Terminado==0 don't execute, but doesn't works…

    Thank you.

    • I’m not sure what you’re trying to achieve here – normally you would create the “ISR” function and it gets called every time the interrupt is triggered.

      If Terminado is declared volatile then that should work:

      volatile int Terminado = 1 ;

      at the outside level of your program.

      However, the way the system works is that one interrupt can be queued up. Your interrupt code will not be called again until it’s exited, so using the barrier like that isn’t needed here.


  41. Hey

    I’m having a bit of trouble with the digitalRead() function, I’m using it in an if function like so

    If (digitalRead(0) == 1) {
    R = 1;

    Simple as, but when I run it with gpio4 (or 7 for wiringPi) set as and output and value 0, it still sets R to 1. Any idea why?


    • Sorry I forgot to say that Gpio4 is wired straight to gpio17 which is what is being read

      • Do stick a resistor between the 2 just in-case – anything small – like 220 or 330Ω.

        So try this:

        gpio -g mode 4 in
        gpio -g mode 17 out

        then connect the wire


        gpio -g write 17 1
        gpio -g read 4
        gpio -f write 17 0
        gpio -g read 4

        You should see 4 changing.


    • It should work OK that way. Do make sure wiringPi pin 0 (that’s BCM_GPIO 17) is set to an input. Never connect 2 Pi pins together if they’re outputs – you’ll short circuit the system if one is high & the other is low.


  42. Hi Gordon!

    I feel that you isn’t a great fan of cross-compilation, but I using this metode, with Eclipse IDE, to compiling and debugging in a Windows 7 machine raspberry Pi C programs.
    I can write a Hello World and deploy and debug, evererything works fine. But whem I try to put wiringPi in my program I can’t generate a bin file. I receveive this message:
    05:08:59 **** Incremental Build of configuration Debug for project HelloC ****
    make all
    ‘Building file: ../src/HelloC.c’
    ‘Invoking: Cross GCC Compiler’
    arm-linux-gnueabihf-gcc -I”C:\rpi-eclipse\rpi-cross-toolchain\arm-linux-gnueabihf\usr\include” -include”C:\rpi-eclipse\rpi-cross-toolchain\arm-linux-gnueabihf\usr\include\wiringPi.h” -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF”src/HelloC.d” -MT”src/HelloC.d” -o “src/HelloC.o” “../src/HelloC.c”
    ‘Finished building: ../src/HelloC.c’
    ‘ ‘
    ‘Building target: HelloC’
    ‘Invoking: Cross GCC Linker’
    arm-linux-gnueabihf-gcc -L”C:\rpi-eclipse\rpi-cross-toolchain\arm-linux-gnueabihf\usr\lib” -o “HelloC” ./src/HelloC.o
    ./src/HelloC.o: In function `main’:
    C:\rpi-eclipse\workspace\HelloC\Debug/../src/HelloC.c:25: undefined reference to `wiringPiSetupGpio’
    C:\rpi-eclipse\workspace\HelloC\Debug/../src/HelloC.c:37: undefined reference to `delay’
    C:\rpi-eclipse\workspace\HelloC\Debug/../src/HelloC.c:42: undefined reference to `delay’
    C:\rpi-eclipse\workspace\HelloC\Debug/../src/HelloC.c:43: undefined reference to `pinMode’
    C:\rpi-eclipse\workspace\HelloC\Debug/../src/HelloC.c:43: undefined reference to `digitalWrite’
    collect2: ld returned 1 exit status
    make: *** [HelloC] Error 1

    05:09:00 Build Finished (took 811ms).

    Can you help me?


    • I’m not a fan because people keep using many different cross compiling environments and I don’t – I simply have no need for it myself, sorry. So the reality is that I jsut don’t have the time to chase up all the different variants and see how to make them work.

      I don’t use an IDE – I do all my Pi work on the Pi itself, and it “just works”.

      Your undefined references there mean that the environment you’re using is unable to find the library. So you probably have to compile the wiringPi library in some way to make it install the library on your PC first, then configure the IDE to use that library.

      It’s so much easier on the Pi.


  43. Hi Gordon!

    Any chances to port wiringPi to BeagleBone Black? I’m using Pi now, but I have plans to buy a BeagleBone Black, but I couldn’t find nothing close to wiringPi.


  44. Hi Gordon,

    I am new to these things. I want to use the serial coms in a program to tx and rx . The program will send one character only in a event —– happens and always monitor the rx line for any character received. Before implementing this into my program I wrote a simple serial program to test the tx part from the info you had published. This is the program;


    int main (void)

    int fd =serialOpen(“/dev/ttyAMA0”, 9600);

    if(fd<0) { printf("unable open device: \n");}


    return 0;


    I complied it with following command;
    pi@raspberrypi ~/piface/c/examples $ sudo cc -o serialtest2 serialtest2.c -IwiringPi

    I am getting following errors;
    /tmp/ccilxioU.o: In function `main':
    serialtest2.c:(.text+0x14): undefined reference to `serialOpen'
    serialtest2.c:(.text+0x38): undefined reference to `serialPutchar'
    serialtest2.c:(.text+0x40): undefined reference to `serialClose'
    collect2: ld returned 1 exit status

    Can you please let me know what am I doing wrong here. Thanks inn advance


    • The serialOpen() etc. functions are all part of the wiringPi library.


      ldd serialtest2

      to see if it’s being picked up correctly.


  45. Hi Gordon,
    Thanks for your reply. For some reason I could not get it working but I took your advice implemented in the old fashioned way and it is working.

    Thanks once again.


  46. hi Gordon,
    I am trying the LCD libary but when i compile a programm i become this:

    undefined reference to “wiringPiSetup”…
    and all the other LCD wiringPi functions. I compiled with the right method.


  47. Hi Gordon,

    I wrote a simple program in Cpp. when I tried “g++ myrasp.cpp” then it gives following error:

    myrasp.cpp: (.text+0x1c) undefined reference to `wiringPiSetup’
    myrasp.cpp: (.text+0x7c) undefined reference to `digitalRead’
    collect2: ld returned 1 exit status

  48. Dear Gordon,

    thank you for implementing that. I played around with some examples and everything worked thanks to your good documentation.


  49. Dear Gordon,

    thank you for implementing that. I played around with some examples and everything worked thanks to your good documentation.

    The Analog interface board, i will check … its good … the adc value is printing the LX terminal window … how to update the same adc value in web server ?
    how to print the adc value in web page ?

  50. Gordon,

    Since Raspbian is not a true RTOS, how reliable is the PWM? Any suggestions/tricks to make it as close to RTOS as possible?

    • The hardware PWM is fine. my softPwm module – well it’s OK for LED brightness and simple motor speed control. It does suffer from jitter, but thats unavoidable. You can minimise jitter by running the thread at high priority and using a Linux real-time schedulling priority – softPwm already does this. There are other steps you can take such as stopping all logging, and all other unneeded processes (such as X windows), but it’ll never be perfect – even if you get one of the real time Linux kernels running on it, there is still the hardware DRAM refresh that will get in the way.

      However I’ve read about people using the Pi to control a quadcopter and balancing robot, so maybe it’s not that bad…


  51. Hi Gordon,

    Do you know any TCP/IP library in C/C++ for the Raspberry Pi?
    I am trying to build a bridge RF-Ethernet in the Raspberry, but it’s missing the TCP/IP part.

    Best regards,
    André Gomes

  52. Hey Gordon,

    I have some trouble with the digitalRead function.
    I have an optocoupler input on gpio 7.
    with “gpio read 7” it works as expected.
    When i try it in c I only get 0 back from digitalRead(7) even when it should be HIGH.
    Here is my code:

    int main (void) {
    int pin7;
    pinMode (7, INPUT);
    while (1) {
    pin7 = digitalRead(7);
    printf (“In7: /d \n”, pin7);
    delay (50);
    I do not see why it should not work. Do you have any idea?