WiringPi

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!)


WiringPi is an Arduino wiring-like library written in C and released under the GNU LGPLv3 license which is usable from C and C++ and many other languages with suitable wrappers (See below)

You may be familiar with the Arduino… Briefly; Arduino is really two things; one is a hardware platform, the other software, and part of the software is a package called Wiring. Wiring is the core of the input and output for the Arduino, so I thought it would be good to replicate that functionality (or a good usable subset) on the Raspberry Pi.

The Raspberry Pi has a 26-pin General Purpose Input/Output (GPIO) connector and this carries a set of signals and buses. There are 8 general purpose digital I/O pins – these can be programmed as either digital outputs or inputs. One of these pins can be designated for PWM output too. Additionally there is a 2-wire I2C interface and a 4-wire SPI interface (with a 2nd select line, making it 5 pins in total) and the serial UART with a further 2 pins.

The Revision 2 Raspberry Pi has an additional 4 GPIO lines on a separate connector which you have to solder onto the board.

The I2C and SPI interfaces can also be used a general purpose I/O pins when not being used in their bus modes, and the UART pins can also be used if you reboot with the serial console disabled, giving a grand total of 8 + 2 + 5 + 2 = 17 I/O pins.

WiringPi includes a command-line utility gpio which can be used to program and setup the GPIO pins. You can use this to read and write the pins and even use it to control them from shell scripts.

WiringPi Resources

Additional Libraries

The PiFace board:

WiringPi fully supports the PiFace board too. See this page for more details.

Other wiringPi resources:

Pin numbering

WiringPi supports both an Arduino style pin numbering scheme which numbers the pins sequentially from 0 upwards, as well as the Raspberry Pi’s native BCM_GPIO pin numbering scheme.

  • Note that when using the BCM_GPIO numbering scheme, you must take into account the board revision! Some pins changed their meaning and numbers from revision 1 to revision 2. Using the wiringPi pin numbering scheme caters for these changes and progams will run un-changed on their board revision.

WiringPi normally uses a very low-level mechanism to access the underlying hardware – this results in very fast access, however the down-side is that your programs need to be run as root, so in addition to this, wiringPi has the ability to use the traditional /sys/class/gpio/ style interface, and if the GPIO pins have been exported and had their ownership changed appropriately, then applications using the wiringPi library, can be run without root privileges.

A supporting program, gpio, allows you to export and unexport the devices through the /sys/class/gpio/ interface. This program is a set-uid program and can be run as a normal user. The gpio program can be used to control the GPIO pins in its own right, allowing easy testing of the GPIO interface from the command-line or simple shell scripts.

Additional information can be found on the Raspberry Pi Wiki pages.

 

Comments

WiringPi — 313 Comments

  1. Hi Gordon,
    I came to your utility as I am trying to emulate a Raspberry board under Qemu (same rootfs seeds as the original released).
    I’d like to play with GPIOs and I suppose I need a driver to take control of them through the /sys/class/gpio/ folder. In fact, it seems there doesn’t exist any such dir at the moment in my Raspberry emulated enviroment.
    I though your package could assist in doing this (not sure though!).
    However, both your code and Gert’s return an error while mapping GPIOs:

    wiringPiSetup: mmap failed: Invalid argument
    if ((int32_t)gpio < 0)
    {
    fprintf (stderr, "wiringPiSetup: mmap failed: %s\n", strerror $
    return -1 ;
    }
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    http://elinux.org/RPi_Low-level_peripherals

    if ((long)gpio_map < 0) {
    printf("mmap error %d\n", (int)gpio_map);
    exit (-1);
    }

    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    It seems the casted value of gpio_map is < 0…
    My question is very basic as I am a newbie in the embeeded world: has it something to do with my emulated system and if so, why and what should I do to solve this issue and succeed in easily accessing GPIOs?
    I really thank you for your kind attention and assistance.
    Best regards,
    Frank

    • Hi Frank,
      My suspicion is that it’s QEMU that doesn’t have the memory mapped for the GPIO and simply insn’t emulating the GPIO at all, and that once you get a real Pi this will “just work” for you…

      Gordon

    • Not right now – there are a couple of I2C drivers on the go that I’m aware of (check the R-Pi forums for more), however I would like to put together a “proper” devicedriver for this GPIO stufff.
      Gordon

  2. Just got some of my Arduino stuff ported to Raspberry Pi!
    Thanks for doing some great work.

    if you add

    #ifdef __cplusplus
    extern "C" {
    #endif

    and

    #ifdef __cplusplus
    }
    #endif

    to your wiringPi.h then it plays nicely with c++ code.

      • Dear Gordon,

        Keep up the good work. Can you thing us any plans for the new release? I want to embed the lib in a C++ program.

        Thanks.

        Ruald.

        • Rauld,
          Looks like I forgot to reply to your comment – sorry for being a month late! However the current version of wiringPi.h has the “right stuff” in it to make it acceptable to c++

          -Gordon

  3. Hi Gordon, awesome work… this looks like it will be a huge help to many Pi users who want to experiment with GPIO. Unfortunately, I’m a .NET developer, and I have Mono running on my PI. I’d love to get your code converted to C# so all us .NET guys can make use of it too. What do you think of the idea of sending me the C source code and I’ll have a go at converting it to C#? (I’m assuming the source files are not in the download, but havent checked closely yet).

    • I’ve really no idea where to begin there – never used any Mono/C#/.net stuff – ever.
      But yes, the source is there, so use it as you need to. It’s all part of the .tgz file.

      -Gordon

    • Hi Stuart,
      did you ever get this converted to C# or .net? I’m very interested in your work.

  4. Hi Gorden,

    According to my testing, it seems either the pin diagram is wrong or your code – MOSIO/MISO have been swapped over (easily done) and CE0/CE1.

    The code change:-

    static int pinToGpio [] =
    {
    17, 18, 21, 22, 23, 24, 25, 4, // From the Wiki – GPIO 0 through 7
    0, 1, // SDA0, SCL0 – The I2C pins
    8, 7, // SPI – CE0, CE1 —- was 7,8
    10, 9, 11, // SPI – MOSI, MOSO, SCLK —- was 9,10,11
    14, 15, // UART – Tx, Rx
    } ;

    Thanks again for the library and the nice easy install 🙂

    • Your quite possibly right. I updated the diagram on my page this afternoon when comparing to the new diagram on the Wiki and I’m sure it’s wrong compared to the circuit diagram.
      Time to re-do the 15-led setup and go back and double-check!
      Cheers,
      -Gordon

  5. Gordon
    Thanks for you wiring Pi code, I have used it with JNI to get my Java code interfacing with GPIO pins. I am now trying to extend it to do the i2c interface and was trying to setup the #defines when I noticed the PWM defines were not what I was expecting. Your code has…
    #define PWM_CONTROL 0
    #define PWM_STATUS 1
    #define PWM0_RANGE 4
    #define PWM0_DATA 5
    #define PWM1_RANGE 8
    #define PWM1_DATA 9
    whereas the BCM2835 describes , for example , the Range registers as being offset as follows
    RNG1 0x14 and
    RNG2 0x20. (I note also the spec refers to RNG1 and RNG2 instead of the #defines PWM0 and 1)

    Clearly your code works as I can see the LED correctly varying in intensity, but I cannot see how the offset work ?
    I was trying to do the same for I2C(BSC) registers and I had the following

    #define I2C_0 (BCM2708_PERI_BASE + 0x205000)
    #define I2C_1 (BCM2708_PERI_BASE + 0x804000)

    #define I2C_CONTROL_OFFSET 0x0
    #define I2C_STATUS_OFFSET 0x4
    #define I2C_DLEN_OFFSET 0x8
    #define I2C_SLAVE_ADDRESS_OFFSET 0xc
    #define I2C_DATA_FIFO_OFFSET 0x10
    #define I2C_CLOCK_DIVIDER_OFFSET 0x14
    #define I2C_DATA_DELAY_OFFSET 0x18

    but now I am not sure I have understood correctly.

    Many thanks for any help
    Steve

    • PLEASE IGNORE MY PREVIOUS EDIT, I HAVE NOW WORKED OUT WHAT THE OFFSETS ARE.
      Cheers
      Steve

        • Gordon
          I have another query which you may be able to help with. In your wiring code you have some clock register code e.g :-
          #define CLOCK_BASE (BCM2708_PERI_BASE + 0x101000)

          and ….
          #define PWMCLK_CNTL 40
          #define PWMCLK_DIV 41

          where is the definition of these clock registers as I have looked in the BCM2835 manual and cannot find any info.

          I need to slow the PWM clock down so want to understand what values are permissible, and hopefully also not break any other clocks/timers.

          Cheers
          Steve

          • The answer is “I wish I knew”. As is mentioned in the code (somewhere!) I based this on some early code released by Gert (or Dom?) and I just copied their code – and as it seemed to work, I left it at that!

            Your right though – it’s not in the peripherals manual. … I’ll see if I can get some more details on it though.

            -Gordon

  6. Brilliant project! Now my Pi will be almost as useful as my Arduino! 🙂

    Will download and play tonight!!! Keep up the good work.

  7. Hi Gordon,
    thanks for the great library – works really awesome!

    But the compiler gave me an warning, that “malloc” was declared implicit!

    After adding “#include ” into the wiringPi.c everything works fine for me!

    Once more a big thank you,
    Marco

    • Near the top, you can put in

      #include <malloc.h>

      to make it quieter! (wondering if that’s what you did, as my first edit of this reply didn’t include the stuff inside angle brackets!)

      -Gordon

  8. Hi Gordon,
    This is great! Miles better than the OS file system method — get some really good speed. Any chance you could make a Python API version please?

    I believe there is a change required to wiringPi.c :
    Test on NUM_PINS removed from digitalWrite() because “pin” parameter may already be GPIO which has values >= 17. This now matches the style of the other functions (i.e. only test for NUM_PINS if WPI_MODE_PINS).

    void digitalWrite (int pin, int value)
    {
    int gpioPin ;

    // if ((pin = NUM_PINS))
    // return ;

    if (gpioPinMode == WPI_MODE_PINS)

    Thanks.
    John.

    • Another bug, another day… 😉
      Looks like one function I overlooked when adding in the code to use the “real” GPIO numbers. Will update it later today.

      thanks,

      -Gordon

      • following up myself – I’ve uploaded a new version of wiringPi to fix this issue and add in some more functions – serial port handling and a few more things from Arduino land – shiftIn and shiftOut. These are separate modules in the libary so won’t affect any existing code.
        -Gordon

  9. Hello Gordon,

    thanks for sharing. I just put together a wrapper for freepascal / Lazarus. Looks like it works quite well.
    http://www.lazarus.freepascal.org/index.php/topic,17404.0.html

    Have you seen this project?
    http://www.susa.net/wordpress/2012/06/raspberry-pi-pcf8563-real-time-clock-rtc/
    Its code to allows I2C Interfacing and seems implemented just like your library. I don’t know C enough, but it would be great if the 2 libraries could be combined.

    Thanks again!

    Alex

    • Hi,

      There are now I2C and SPI drivers for the Pi in the Linux kernel, so I’m holding off writing my own code to drive them until I’ve tested the kernel ones for myself.
      It’s a long time since I’ve programmed in Pascal though – glad it’s working for you though!
      Cheers,

      -Gordon

  10. Hi Gordon,
    Great work with the GPIO stuff for Rasp Pi.

    I am using it as the basis for an IR transmitter tool.
    I can (almost) get IR pulses coming out of it, but I think I need to set the PWM freq to 38Khz. Is that possible with your library?

    Regards

    Nick

    • Not directly, however if you want to hack the code 😉

      Look in the wiringPi.c code for where it sets the clock and PWM mode. You’ll need to fetch the BCM ARM Peripherals manual too – that’ll help you find it.
      I do have plans to allow for varying the PWM frequency and mode, but not had time to really look into it though.
      -Gordon

      • OK, so I had a look at the manual, and the code.

        It looks like I can use value 505 as the clock divider.
        So, 505<<12 in the code, instead of 32<<12.

        Because, 19.2MHz divided by 505 = 38Khz.

        I will give that a go.

        Regards

        Nick

        • Nah,
          Tried it, but didn’t work.

          Think I need a oscilloscope to debug this, and measure the exact frequency generated.

          Regards

          Nick

          • Hi Gordon,
            I made some progres with the PWM IR transmitter.
            The problem I originally had was with turning PWM off.
            I was using pwmWrite(1, 0) to turn it off, which didn’t appear to work, but changing the pin to an INPUT did do the trick.

            So, now, my IR receiving device is getting IR pulses, but it’s having a difficult time decoding the pulses because the timing is all over the place.
            Although there is some margins to the pulse timings – the Raspberry Pi nanosleep function isn’t accurate enough. I guess this is because the Debian Wheezy OS I am using isn’t really a real time OS.

            Anyway, I have been told that DMA over PWM is possible as an alternative, so I will have a look at that soon.
            Unless you already have some example code to do DMA over PWM for the Pi?

            Regards

            Nick

          • I need to spend a little more time looking at the manual for the PWM drivers – there are 2 modes to drive it in, but setting it to zero (or 1023) ought to drive it low 100% of the time or high 100% of the time…
            However, yes, making it an input (or output) ought definately to turn it off!

            Timing – yes, nanosleep has a minimum resolution overhead, and then it cal take longer than you give it too. You may want to have a look at my LED driver program to switch your program into high priority though – have a look here:

            https://projects.drogon.net/7-segment-led-display-for-the-raspberry-pi/

            the link to the software is near the end.

            And while DMA is possible – I understand it’s used by the audio driver, I’ve really no idea how to set it up. (Although looking at the audio drivers might be helpfull here!)

            -Gordon

          • The nanosleep function is a real pain. The best resolution I can get is almost 100us which is so much slower than the Arduino which can manage about 4us with delayMicroseconds.

            I am not really familiar with Linux but as best I can tell you need a version of Linux which supports High Resolution Timers to get better accuracy.

            I have tried CPU intensive loops waiting for gettimeofday() to reach a given value but even at the highest priority periodic interrupts screw up the timing and there does not seem to be a simple way to turn off interrupts for critical timing code.

          • I know… It’s a good attempt, but not perfect.

            I think we just have to admit that the Pi is not really a device aimed at “hard” real-time control. There is a lot we can do to help things along though, and busy-loop waits are achievable, but they are just that – busy-loop waits consuming all the CPU… Which in itself might not be that big an issue on the Pi which is more or less going to be single-user use most of the time anyway – Linux will poke it’s head in every now and then to service stuff like USB, Ethernet and so on though.

            I’ve got a scope coming tomorow, so I may be better able to check some other stuff too when I get a chance.

            I don’t think the BCM ARM has a high resolution timer though.

            You can turn interrupts off though – not sure I’d recommend it myself – if you search the raspberrypi.org forums for the logic analyser threads… I think they run into an issue that ultimately may not be possible to “fix” though and that’s the GPU doing memory operations like refresh, etc. You really want static RAM for a properly deterministic system…

            So we have a system that’s good enough for simple LED/Switch/Motor control, but possibly not good enough for really fine-grainned control.

            -Gordon

          • I found a great replacement for delayMicroseconds. It does not stop interrupts but it looks promising

            http://www.thebox.myzen.co.uk/Raspberry/Magic_Wand.html

            This is an extract from the code on that page accessing the internal timer.

            #define BCM2708_PERI_BASE 0x20000000
            #define TIMER_BASE (BCM2708_PERI_BASE + 0x00B000) /* TIMER ARM controller */
            char *timer_mem, *timer_map;

            // Access to the ARM timer
            void setup_timer_file(){
            /* open /dev/mem */
            if ((mem_tmr = open(“/dev/mem”, O_RDWR|O_SYNC) ) < 0) {
            printf("can't open /dev/mem \n");
            exit (-1);
            }

            /* mmap TIMER */

            // Allocate MAP block
            if ((timer_mem = malloc(BLOCK_SIZE + (PAGE_SIZE-1))) == NULL) {
            printf("allocation error \n");
            exit (-1);
            }

            // Make sure pointer is on 4K boundary
            if ((unsigned long)timer_mem % PAGE_SIZE)
            timer_mem += PAGE_SIZE – ((unsigned long)timer_mem % PAGE_SIZE);

            // Now map it
            timer_map = ( char *)mmap(
            (caddr_t)timer_mem,
            BLOCK_SIZE,
            PROT_READ|PROT_WRITE,
            MAP_SHARED|MAP_FIXED,
            mem_tmr,
            TIMER_BASE
            );

            if ((long)timer_map >2)); // the value of free running counter
            current_count = count_at_start;
            while( (current_count – count_at_start) >2));
            } // hold until the time is up
            }

          • Hi Keith,

            Yes, that’s the code from Mikes wand – I’ve had a look at it recently and it’s possibly better for very short delays. I’ve got some hardware lined up to do some timing tests on the Pi to see what is going to work the best for general use – I’m sort of trying to keep things as “linux friendly” as possible for now though, so calling the system routine that I do in delayMicroseconds is “friendier” for other processes – at the expense of a bit more latnecy, but when I’ve had time to do more tests I’ll be adapting wiringPi as I think is best.

            Thanks,

            -Gordon

    • There is a shiftIn and Out library in wiringPi, but to do things like measure frequency is somewhat tricky due to the pre-emptive multi tasking nature of Linux – your program can be interrupted at any point and Linux can then do something else – that would make frequency measurements somewhat tricky.

      However, there are a few tricks you can do to get your program to run at a higher priority and a few hacks like turning off interrupts..

      Have a look at my LED driver example for some code that will run your program at a high priority:
      https://projects.drogon.net/7-segment-led-display-for-the-raspberry-pi/
      a link to the code is near the end of the article.

      So you could sample for a given period of time, then sample again and again, then compare the 3 samples – the 2 closest to each other are probably the frequency you’re after….

      As for the hh10d – that has an I2C interface and sould work directly with the I2C hardware on the Pi with the new I2C kernel driver.
      I did a project to read the SHT-15 sensor on the Pi, but that was pure bit-banging, but it worked well.

      -Gordon

      • Thanks.
        HH10D needs the I2C only to read the calibration constants, it outputs the current humidity as frequency.

        • Ah right. I’ve not read the full details. Seems a somewhat intersting way to get the data back… Not sure how reliable the Pi will be reading it though.
          -Gordon

  11. Thanks for posting the Shift Library on the website but I don’t seem to get a clock pulse on the pin I defined – This is my “simple” code

    #include
    #include
    #include
    #include

    #include

    int main(void){
    int LatchPin=2,DataPin=0,ClockPin=1;
    printf(“Raspberry Pi Shift Out Test\n”) ;
    printf(“%d\n”,LatchPin);
    printf(“%d\n”,DataPin);
    printf(“%d\n”,ClockPin);
    if (wiringPiSetup() == -1)
    exit (1) ;

    pinMode(LatchPin, OUTPUT);
    pinMode(DataPin, OUTPUT);
    pinMode(ClockPin, OUTPUT);

    shiftOut(DataPin,ClockPin,1,85);

    digitalWrite(LatchPin, 1);
    delay(100);
    digitalWrite(LatchPin, 0);
    return 0;
    }

    I just can’t see what’s wrong

    Thanks

    Paul

  12. Gordon,

    Downloaded wiringPi the other day and got it working – thanks – so I was able to test out my breadboard. Then I installed Dom’s latest kernel to get the interrupt patches as I’m working on a interrupt module – that install carefully removed my wiringPi installation as to get it to compile I’d stuck it in /usr/src/ which got cleared out by the new install 🙁 Then I saw your latest version of wiringPi which has interrupt capability so I thought I’d give that a go first. But now when I download it I can’t decompress it; I get “gzip: stdin: not in gzip format”. xarchiver also complains ‘Archive format not recognised’. What am I doing wrong?

    • Well, its working now… can’t explain it but another cold reboot (not just “shutdown -r now”) and all is well 🙁 dont you just hate that…

      • Hi Glad it’s going now – not sure wh a kernel update woulr remove wiringPi – a whole systems upgrade might though as it’s not (yet) installed as a Debian package
        However – the current version online doesn’t have the interrupt handling code in it – but once I finish the write-up on it, I’ll be uploading it hopefully later this morning.
        -Gordon

  13. Hi Gordon, thanks for the info.

    Do you have any examples of the interrupt driven GPIO input? as opposed to the continuous polling that runs the CPU round in circles 🙂

    Thanks,

    Ashley

    • Hi,
      The example in the latest wiringPi release has a program ‘wfi.c’ and that waits for an interrupt generated via the GPIO. Internally it uses the poll() system call, but this is misleading in it’s function – the kernel doesn’t busy-loop poll for the signal, but really does wait for the interrupt to happen, then it releases your program.

      To effect this, you need to create a thread or concurrent process inside your main program to monitor to the interrupt, then it can take appropriate action when the interrupt happens.

      So have a look at the example – I think that’ll answer your needd – or provide you a framework to build on.

      -Gordon

      • Hi Gordon! Thanks for your pointer to wfi.c, unfortunately I couldn’t get any result from it, but I wasn’t sure if it was expecting the rpi pin 0 or bcm pin 0, however it could be my button circuit. The push-to-make button has a 10k resistor pulling to neg.

        I read your posts over here http://www.raspberrypi.org/phpBB3/viewtopic.php?f=33&t=10377 and the example Gpio-int-test.c posted by a fellow pi-maker does work with my button on rpi gpio0 but I get an interrupt trigger at the start of the program and then 2 for every press – this makes sense to me in a way because the state has changed twice – but I thought that the ‘edge’ parameter was supposed to eliminate this.

        Any pointers or advice you can share would be appreciated.

        Thanks again,

        Ashley

        • OK. I’d start with a single button connected to GPIO 0 – this is wiringPi pin 8, or the SDA0 pin on the edge connector. (pin 3 on the connector just to confuse you more) This pin has a 1.8Kohm pull-up resistor on the Pi’s board, so connect a switch from this pin to ground. No resistors needed – and a 10K resistor would not be nearly enough to make it work anyway (or it shouldn’t, but it does appear to work for you – quick calculation: R1 = 1800, r2 = 10000, vIn = 3.3, vOut – r2 / (r1 + r2) * vIn = 10000 / (1800 + 10000) * 3.3 = 2.8V which I’m not sure is low enough at all to pull the line to logic zero….

          Quick check with:

          gpio -g mode 0 in
          gpio -g read 0

          and expect it to read 1 when the button is open, and 0 then closed.

          then you can move to using the interrupt mode:

          gpio edge 0 falling

          then run the program.

          If you look in the examples directory of wiringPi, then there is a wfi.c program which demos it.

          You are probably getting 2 interrupts due to switch bounce.

          -Gordon

          • Hi Gordon, thanks again for your help!

            I wired up as you describe and still got the 2 counts from each press with your code ‘wfi.c’ so I extended your delay to 1000 microseconds which cured the ‘switch bounce’.

            However I have noticed that it stills utilises ~100% CPU instead of being idle like the poll() statement does in the other C example.

            Is it possible to utilise a ‘poll()’ equivalent in wiringPi?

            Thanks again,

            Ashley

          • The 100% cpu is coming not from the interrupt handler, but from the main program – which is sitting in a loop, printing the counter.
            If you put

            delay(10);

            in the loop on the main program you’ll watch the cpu usage drop to near zero. IT was just a demonstration that the main program could carry on independant of the interrupt routine. Actually, you might want to put in something like

            delay (5000);

            after the piUnlock() statement, which is a 5-second delay, then push the switch a few times…

            A simple delay like that is a rather crude de-bounce though, you may want to do something like check the time between interrupts until the time is less than a pre-determined interval. You can use the millis() function to return an incrementing number of milliseconds since your program started.

            It’s not impossible the underlying interrupt handler is double-triggering though, but I need to do some more experiments myself on that.

            -Gordon

          • Hi Gordon, thanks for your help and the updated wfi.c

            It does reduce the CPU usage right down to ~0.5% as you said, but the delay means that the interrupt doesn’t ‘register’ for n seconds, that’s not a major issue..however:

            The only problem is I am still sometimes getting increments of 2 when I only briefly press the button, my only guess is that the change from 1->0 and 0->1 are registering individually…

            Ashley

          • The delay in the main loop doesn’t stop the interrupt registering – just printing. The interrupt still happens and is actioned. Just think of it as 2 separate programs running in parallel.
            I’ll need to do some tests myself with a digital signal that’s not prone to bounce – I guess it’s possible that the interrupt is happening twice, but with my modified program I could reliably get one Interrupt per switch push.

            -Gordon

          • Gordon – I was driving this with a signal generator when I did the timing measurements (as discussed on the other thread under ‘Functions’). I can confirm there is no double triggering when the input is clean.

            Irving…

          • That’s really good to know, thanks!

            I guess there must be some really bouncy switches out there then – and it does also show that the Pi can easily capture the multiple interrupts too – so good and bad there!

            Thanks again,

            -Gordon

          • Thanks Irving, Gordon, for your help, all I can say is don’t buy cheap Maplin push switches 😉 – I will try and find a few different ones to test with and report back to be sure.

            Ashley

          • Thanks chaps, it appears it was the switch, after trying 2 more push switches and different wiring, I found the original switch was at fault (it actually cost 3 times as much as the new ones too!). Thanks again for your help in getting to the bottom of it… I can actually start putting it to use now 🙂

            Cheers
            Ashley

  14. This is amazing work. Thank you for this.
    Can this library be used to run a servo off the GPIOs?

    • Possibly.
      The first hurdle is interfacing the servo – you’ll need a driver of some sort to boost the Pi’s 3.3v
      to whatever the servo needs.
      then there’s the actual drive mechanism – for a radio-control type servo where you feed it a PWM signal
      which it then translates into positional info, you may need to check the PWM frequency (sometging on my ever
      growing to-do list).
      The down-side is that there is only one PWM output on the Pi, so only one servo may be controlled in that
      manner.
      -Gordon

      • Thanks Gordon,
        I saw in one of your other pages the reminder that pi is 3.3v! Very important because I cut my teeth on the 5v arduino. Based on your response it sounds all very possible, but this also enforces my growing feeling that the marriage between arduino with its analog pins, PWM pins, software, and shield ecosystem is likely a very powerful combination. Thanks again for your response and your awesome work on Wiring Pi!

        • It’s possible to drive 5v peripherals from 3.3v (usually), but you have to make sure that they can never drive 5v back to the Pi – e.g. when driving bi-directional devices such as the LCDs I’ve been experimenting with recnently. (in that scenario, I hard-wire the R/W pin to ground!)
          Cheers,
          -Gordon

  15. You may wish to look at this library for good stuff for SPI implementation:

    —Links removed—

    • The SPI driver built into the latest kernels supported by the Foundation work really well and it’s a tandard Linux interface, so there is no point in even thinking of using anything else

      I’m using the kernel SPI driver to drive the PiFace board and the A/D and D/A chips on the Gertboard.

      Cheers,
      -Gordon

      • Hi Gordon,

        Based on your Gertboard sample, I have created a sample for my D/A board. First addressing just one D/A.

        #define B_SIZE 500
        while (1) {
        #ifdef TIMING
        then = millis () ;
        #endif
        for (c = 0; c %9.4f samples/sec \n”, 1 / (((double)(now – then) / 1000.0) / (double)(B_SIZE))) ;
        #endif
        }

        With as result the following :
        14 mS, 0.0000280 S/sample -> 35714.2857 samples/sec
        15 mS, 0.0000300 S/sample -> 33333.3333 samples/sec
        15 mS, 0.0000300 S/sample -> 33333.3333 samples/sec

        Do you get the similar timing for putting 16 bits on the SPI device?

        Thanks, Arjan

        Note : I’ve changed wiringPiSPIDataRW –> int wiringPiSPIDataRW (int channel, unsigned char *data, unsigned char *rx_buf, int len) so my table with output data is not overwritten.

  16. Hi Gordon,

    Thanks for your work on this – it’s got me tinkering with electronics which I never thought would happen.

    I’ve put together bindings for Tcl using Gadgetoid’s SWIG input file so for anyone who would like to use WiringPi from Tcl it’s all at: https://github.com/davidb24v/WiringPi-Tcl.git

    I’m also playing with accessing the library from gfortran with the use of the standard ISO_C_BINDING module. Why? Well, because I can…

    Regards,
    Dave

  17. Hi Gordon,
    I’ve been playing around with the PWM control using your gpio program. I hooked a scope up to the Wiring Pi pin 1 (GPIO pin 18) and noticed that when the PWM value is changed between 0 and 1023, the duty cycle of the signal is indeed changing from 0% to 100% as would be expected. However, the frequency of the PWM signal itself is also changing. For example, at pwm=511 (50% duty) the frequency (over one period of the PWM signal) is 300kHz. Interestingly, with pwm=255 (25% duty), the frequency of the signal drops to 150kHz. I would normally expect the frequency to remain static and just the duty cycle change.

    • It’s something on my to-do list to look into. I copied the PWM code from Gert’s original and as it seemed to work well enough to control an LED and a motor, I just assumed it was OK, however I know that the chip has a couple of different modes to run the PWM in, and a few others have expressed an interest in changing the frequency, etc. so I have a little ‘scope on order myself and am going to have a play with it soon to better understand how it’s working.
      -Gordon

  18. You are a god of programming!
    Thanks for wiringpi!
    With this solving robotycs is very simple thing.

  19. Hello,
    how to use the wiringPi as user (not root)
    wiringPiSetup: Unable to open /dev/mem: Permission denied

    thx wally

    • To use it as an ordinary user without being root, or using sudo … You need to use the Sys interface. This uses the system provided mechanism that exists in the /sys/class/gpio heirarchy.

      So.. The first thing to do is work out what pins you are using (and note that all pin numbers in this mode use the BCM_GPIO numbering scheme), then you use the gpio command to “export” the pins. So if you want to use pin 17 for an input and 18 for an output, run the following command:

      gpio export 17 in
      gpio export 18 out

      That will export the pins, and change ownership of the special files so your program can use them.

      Next, you make sure your program initialises wiringPi as follows:

      x = wiringPiSetupSys () ;

      after that, you can use digitalWrite () and digitalRead () as before, but do note that many things are not supported in Sys mode – changing a pins direction, using the internal pull up/down resistors (althoug hyou can set them using the gpio program).

      Let me know if that helps.

      -Gordon

      • Sure this helps, thank you very much.
        I remember i had few years ago similar problem with parallel port access on linux and i got it solved modifying some udev-rules.
        The limitation on using the Sys interface are painful 🙁
        Mainly i need Serial communication and 2 Interupt service routines on 2 input pins.
        wally

        • At present, interrupt handling must use the Sys interface anyway, although I’m looking at alternatives.

          To setup a pin for interrupts:

          gpio edge 18 rising

          will make pin 18 an input and set the trigger to a rising edge.

          -Gordon

  20. Excellent library, Gordon, many thanks!

    Please take a look at the BROADCOM BCM2835 ARM PERIPHERAL manual, page 7. It talks about precautions when writing/reading to/from peripheral memory, so data can be guaranteed to be “in order”.

    Best regards!

    • I had a look when I first got the document and didn’t think it would be an issue then, however the issue can happen when reading from different peripherals. I’ll have a look again and see if there is a real issue here, however it’s not something I’ve observed happening during my own tests, but I guess if there’s a possibility, not natter how small it ought to be catered for.
      -Gordon

  21. Hi All, I have problem with installing wiringPi on python

    I got error message when sudo python setup.py install, need help!!!!

    running install
    Checking .pth file support in /usr/local/lib/python2.7/dist-packages/
    /usr/bin/python -E -c pass
    TEST PASSED: /usr/local/lib/python2.7/dist-packages/ appears to support .pth files
    running bdist_egg
    running egg_info
    writing wiringpi.egg-info/PKG-INFO
    writing top-level names to wiringpi.egg-info/top_level.txt
    writing dependency_links to wiringpi.egg-info/dependency_links.txt
    reading manifest file ‘wiringpi.egg-info/SOURCES.txt’
    reading manifest template ‘MANIFEST.in’
    writing manifest file ‘wiringpi.egg-info/SOURCES.txt’
    installing library code to build/bdist.linux-armv6l/egg
    running install_lib
    running build_py
    creating build
    creating build/lib.linux-armv6l-2.7
    copying wiringpi.py -> build/lib.linux-armv6l-2.7
    running build_ext
    building ‘_wiringpi’ extension
    creating build/temp.linux-armv6l-2.7
    creating build/temp.linux-armv6l-2.7/WiringPi
    creating build/temp.linux-armv6l-2.7/WiringPi/wiringPi
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.7 -c WiringPi/wiringPi/lcd.c -o build/temp.linux-armv6l-2.7/WiringPi/wiringPi/lcd.o
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.7 -c WiringPi/wiringPi/piHiPri.c -o build/temp.linux-armv6l-2.7/WiringPi/wiringPi/piHiPri.o
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.7 -c WiringPi/wiringPi/piThread.c -o build/temp.linux-armv6l-2.7/WiringPi/wiringPi/piThread.o
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.7 -c WiringPi/wiringPi/wiringPiFace.c -o build/temp.linux-armv6l-2.7/WiringPi/wiringPi/wiringPiFace.o
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.7 -c wiringpi_wrap.c -o build/temp.linux-armv6l-2.7/wiringpi_wrap.o
    wiringpi_wrap.c:125:20: fatal error: Python.h: No such file or directory
    compilation terminated.
    error: command ‘gcc’ failed with exit status 1

    Thanks
    Eugene

  22. Hi Gordon,

    Just like to say a big thank you for wiringpi it’s a great help for us less talented programmers. I have a couple of question/suggestions for improvement:

    1) Can you add DESTDIR to the makefile to make distribution packaging a little easier?

    2) I have been looking as the pwm output on my oscilloscope and to my surprise the output was not as I expected in that as you adjust the pulse width the frequency changes. In fact what is happening here is that for values between 0-512 the high level pulse remains constant and the low level is extended, once above 512 the reverse happens (low level constant and high level changes). Peak frequency is 300kHz with a value of 512 and drops below 18kHz for low and high values. The other point is that you need values of exactly 2^n for stable pulses up to 512 and 1024-2^n for stable pulses above 512.

    I have experimented with wiringpi.c to see is I can achieve a more traditional pwm output and I am happy to report that you can. The solution is to switch to MS_MODE rather than PWM_MODE. The downside of this is that the pwm frequency is rather slow at around 600Hz and even with PWMCLK_DIV set to 2 is still still only 9kHz. I then tried different clock sources and have found that using PLLD as the source with PWMCLK_DIV set to 16 gives a much more respectable pwm frequency of 30.5kHz. Whith these settings the frequency is stable and constant regardless of the pwm value chosen.

    I hope this is of some help,

    Regards,

    Chris

    • Hi,

      the latest versions of wiringPi have 2 additional functions to control the PWM – not documented yet, but they are pwmSetMode() and pwmSetRange(). See the wiringPi.h file for the details and the runes to feed into SetMode. Get the latest via GIT: https://git.drogon.net/

      I’ve been trying to get to grips with the whole PWM frequency thing myself, and it seems it’s not straightforwards. In MS mode, the frequency appears fixed at 600Mhz (as you’ve found), and changing the clock divider doesn’t appear to do anything. (Although you seem to have had it change for you? Intersting…) I have asked Gert at Broadcom about this, but even he’s somewhat confused (and it appears that the person who designed it no-longer works for Broadcom either, from a posting on the raspberrypi.org forums!)

      There’s alsways my softPwm driver though 😉

      As for DESTDIR – I’ll have a look, but /usr/local/include and lib are searched by default though which makes it slightly easier…

      -Gordon

      • Thanks for the reply, I’ll down load the latest version and have a play.

        By the way you can change the MS mode frequency although once set you have to reboot to change it again. There may be a way around this but I have yet to find it.

        Chris

        • Hi Gordon,

          I believe I have found the magic spell that allows the PWMCLK_DIV to be adjusted without the need for a reboot:
          Disable PWMCLK “*(clk + PWMCLK_CNTL) = 0x5A000000”
          Wait for PWMCLK_CNTL bit 7 (Busy) to go low
          Set PWMCLK_DIV “*(clk + PWMCLK_DIV) = 0x5A000000 | (16<<12)"
          Set the clk source "*(clk + PWMCLK_CNTL) = 0x5A000001"
          Enable the clock "*(clk + PWMCLK_CNTL) = 0x5A000011"
          Do the other stuff as per Gerts/Doms values
          And away we go.

          If you look at page 107 of the BCM2835 peripherals document it clearly states that you must not set the clock source when BUSY=1 and that you must not change the clk source at the same time as asserting ENAB which is exactly what you are doing in your code. Page 108 also states under DIVI "to avoid lock-ups do not change this control while BUSY=1".

          Having typed this I now realise that you may not need to disable the clock before setting and it may all be down to checking the state of BUSY before making adjustments.

          Best regards,

          Chris

          • A-Ha. That may just be the key required! Let me do some tests tomorow with the scope and I’ll have a look and see how it works.

            Cheers,

            -Gordon

          • Hi Gordon,

            The frequency adjustment was still getting stuck after a varying number of adjustments. Adding a delay in between setting the clock source and enabling the clock seems to resolve this, at least for me. I used a delay of 10uS as this appears to be popular elsewhere in the code. It may be a case of checking the BUSY flag again but I have not tried this. I’ll be interested to hear how you get on with this. Anyhow must go to work now.

            Best regards,

            Chris

          • Hi Gordon,

            I have just e-mailed you the fixes for the PWM divider. Let me know if they work for.

            Best regards,

            Chris

    • Hi Gordon,

      Do you have the modifications that allow CLK change for MS mode incorporated into your latest release of wiringPi.

      • Sorry. I’ve no idea what you’re on about. This is really designed as comments to my original posting and not a forum, (although I’m now looking at implementing one), so I don’t know what you’re replying to.

        I’m guessin PWM? If so, then you can change the clock divider and range registers, however the Pi’s hardware PWM needs more investigation, but personally, I’ve given up on it as there’s only one and it’s really not that flexible.

        -Gordon

  23. Hi Gordan

    I have a problem. Can we use the wiringPi in cross compilation. I have used it in windows and Ubuntu. It did not work always stuck up with the “not compatible -lwiringPi” error

    Consult the user’s guide for more details about POSIX paths:
    http://cygwin.com/cygwin-ug-net/using.html#using-pathnames
    c:/codesourcery/bin/../lib/gcc/arm-none-linux-gnueabi/4.6.1/../../../../arm-none-linux-gnueabi/bin/ld.exe: error: C:\Users\arouthu\Documents\eclipse\trail1\Debug\libwiringPi.a(wiringPi.o) uses VFP register arguments, trail1 does not
    c:/codesourcery/bin/../lib/gcc/arm-none-linux-gnueabi/4.6.1/../../../../arm-none-linux-gnueabi/bin/ld.exe: failed to merge target specific data of file C:\Users\arouthu\Documents\eclipse\trail1\Debug\libwiringPi.a(wiringPi.o)
    collect2: ld returned 1 exit status
    cs-make: *** [trail1] Error 1

    **** Build Finished ****

    • I don’t know, sorry.

      However I’d have thought if your x-compile environment allowed you to build libraries, then it ought to work.

      Or can you build it on a Pi, then take the .h and .a files and put them into your cross compile environment?

      I compile everything on a Pi these days…

      Gordon

      • Gordon,

        I am a beginner on Linux programming and I am missing something. The compilation works great on the Raspberry Pi itself. I was able to cross compile and build following the tutorial from halherat at http://hertaville.com/. But when I try to add the wiringPi library to my project, I always getting the error “cannot find -lwiringPi” or not defined INPUT, OUTPUT, digitalRead, etc.

        What I have done is:
        – installed wiringPi on the KUbuntu.
        – mount a nfs directory pointing to the wiringPi installed folder on the raspi.
        – replace the files libwiringPi.so.1 and libwiringPi.so.1.0 on the KUbuntu /usr/local/lib from the one found on the raspi.

        I am sure that I am very close but I am missing a config somewhere. When the command sudo make install is executed, what it is change on the Linux exactly?

        I would love to get a remote developpement and debugging envirronment.

        Thanks for helping

        • I do all my Pi development on the Pi itself. The only thing I’ve cross-compiled was a kernel some time back, so I’ve really no idea how your cross-compile environment will work here.

          I imagine you need to cross-compile wiringPi, install its libraries local to your PC, then compile your own projects on that PC, but I’ve really no idea of the actual steps involved.

          -Gordon

    • Realizing this is an older post.

      If you are attempting to cross compile you application, you need to ensure that wiringPi is also cross compiled.

      Following the wiringPi instructions and ending with the .build creates a lib for your current platform, in my case x86. This 64bit libs clearly can not be used on the Pi.

      A simple solution is install wiringPi on you Pi and your CrossPlat system, then scp the contents /usr/local/lib/lib*.so from your Pi to the CrossPlat system in the same location.

      that will get you going anyway… I’ll leave the rest as an exercise 😉

  24. Does this allow me to use my Arduino boards and libraries on the RPI? I need to get my NRF24L01 RF Transceiver working on the Pi so it can communicate iwth an Arduino which also has that transceiver connected (thus enabling me to wirelessly control things attached to the Arduino). Problem is that I have practically no experience in directly controlling hardware. I have always imported libraries in my Arduino code and controlled everything through those libraries. The only hardware I have ever directly read from was a potentiometer and the only thing I have ever directly controlled was a simple LED.

    • arduino boards are generally not compatible due to the voltage difference (typically 5v for arduino and 3.3v for Pi).

      wiringPi is an attempt to be similar to the arduino code, but it’s not a direct replacement for it – although it may be possible to port over some ardino libraries to run on the Pi using it. I do’t know how that RF transciever works though, so can’t comment directly on it.

      -Gordon

      • Is there anything you could say about such ports from Arduino to the Pi in general (thus not my RF transmitter in specific)?

        • Hardware wise – The main issue is going to be the voltage difference if you’re interfacing peripherals – typically 5v for the Arduino and 3.3v for the Pi. Also analog input – there’s none on the Pi, and PWM output – only one on the Pi – unless you do it in software.

          Software wise – while the Pi is faster than the Arduino, timings can be more problematic as there is the underlying Linux operating system, and even if you go “bare metal” there is still things like DRAM refresh and GPU access which may affect software timing loops…

          But in-general it shouldn’t be too hard to convert projects from Arduino land to Pi land – with a little bit of thought and effort!

          -Gordon

  25. Hi Gordon

    Im trying to write a spec file to package wirinPi for the new Raspberrypi Fedora Remix. My problem is when I try to mock build the package I cant seem to get gpio build properly. I will provide a url to the spec file I wrote for this package any help would be appreciated

    I receive the following make error:

    make: *** No rule to make target `/usr/local/lib/libwiringPi.a’, needed by `gpio’. Stop.

    Url to my spec file:
    http://scotland.proximity.on.ca/~agreene/wiringPi/wiringpi.spec

    • Hi,

      I’ve never used any of the RH Linux deriviatives, so I’ve no real idea about their spec files, however – it sounds like the wiringPi library has not been installed before trying to compile the gpio program – if the spec file is interpreted linearly, then that looks to be the case.

      Other things I’ve observed from that file – the wiringPi license is LGPLv3 and if-possible, I’d suggest to use the GIT way to get the latest source – the “Source0” line refers to the older downloads site which is not updated nearly as often as the GIT site!

      Cheers,
      -Gordon

      • thanks for the prompt reply I do realize that’s my main problem but I have to run the makes before I can actually install anything so I’m going to have to figure out a way to work around that but I will update the source info once again thanks for the reply.

  26. Hi Gordon,
    Just wanted to thank you for your excellent tool. I have used it as a dependency for a web based Pi control project ( http://goo.gl/uHRZq ), and of course have credited with this. It has been considerably easier than doing it through PERL, and at least doesn’t seem to need me to escalate privileges for the web server user. Perfect. Thanks again
    Saif

  27. Hi!

    Nice project. I used it, to make my own HD44780-control.
    You write, that it is possible to use the BCM GPIO pin numbering istead of the “easy Arduino” numbering. But in your examples I was only able to find the numbering from 0 to 16. How do I have to write the BCM GPIO in C?

    Thanks

    • If you want to use the native BCM_GPIO pin numbers, then instead of calling wiringPiSetup(), call wiringPiSetupGpio () instead.

      You can also call wiringPiSetupSys () and that will then use the (slower) /sys/class/gpio interface – which means that you don’t need to be root to run your program, however you will need to use the gpio command to pre-export the GPIO pins beforehand.

      I’d suggest sticking to the wiringPi pin numbers if you can – they’ll cope with the pin changes from the Rev 1 to the Rev 2 boards, but if you are using the native numbers, just be aware of the board revision you’re running on.

      -Gordon

  28. Hi!

    Fantastic library! Congratulations!

    I’m having a little trouble with the example test2. If I reboot the RPi and execute it, the first time the led does not shine. After a ctrl-C and executing it again it works OK!

    Any idea why? Can I send you more info to help identify the problem?

    Thanks

    MJ

    • Looks like I might need to go and re-check the test2 code – just to make sure it is doing what its supposed to be doing!

      -Gordon

    • What do you want to do with it?
      rs485 is a multi-drop serial bus – I’m assuming it’s connected here to the Pi’s on-board uart (hard to tell without a circuit diagram of the board though).
      Do you have other rs485 devices to talk to? you’ll probably have to write your own software on the Pi side of things to help you – wiringPi has some serial support in it though – just check the web page, but you’ll also need to check the pages for the devices you’re trying to talk to…

      -Gordon

        • You might want to start with minicom on the Pi side of things – it’s a serial terminal emulator program – run it and configure it to use /dev/ttyAMA0 at the baud rate you want and off you go.

          But I’ve really no experience with rs485, nor a serial to ethernet convertor type thing (unless it’s a terminal emulator that lets you telnet out over the ethernet/ip side?)

          The IO board itself looks simple enough though.

          -Gordon

  29. Followed your guide all the way up to the last make but get the following error..
    make: *** No rule to make target `/usr/local/lib/libwiringPi.a’, needed by `gpio’. Stop.

    Copy of the Makefile… not sure where the archive is supposed to come from.
    http://pastebin.com/JWiWs6SX

    I am using Raspbian 3.2.27+ #250 PREEMPT Thu Oct 18 19:03:02 BST 2012 armv6l GNU/Linux

    • A quick fix is to edit the Makefile and remove the check for libwiringPi.a on the gpio: line, but it looks like I’ve missed a bit out when moving from static libraries to dynamic ones.

      Will check and put up a new version later today.

      -Gordon

  30. Gordon, WiringPi continues to be the gold standard for Wiring style programming of the Pi’s GPIO. Yesterday the Arduino group stated their new 1.5 IDE will allow multiple toolchains allowing multiple target systems, essentially opening the door to allow a compilation of the code in the Arduino IDE to target the Raspberry Pi (using gcc/ARM6). WiringPi would be the obvious mapping of GPIO for such an endeavor. What do you think of such a concept?

    • It sounds interesting – but there are many architectural differences between a Pi and an Arduino platform – e.g. the Pi has pull down as well as pull-up internal resistors and they’re activated in a different manner, so there are a few subtle differences like that. Timing too… So who knows!

      The only thing I’d be intersted in is the “pin” mapping – I’d like to think that any other “wiring” library used the same pin definitions I used rather than the native GPIO pin numbers (which have changed from rev 1 to rev 2 boards!), but…

      However, I don’t use the Arduino IDE myself, so might be a bit out of touch with it all.

      -Gordon

  31. Hello,

    I’m trying to control a servo using the pwm pin. The problem is I want to use wiringPi (or later on the python wrap) but need settings different from default divisor and range. How to change this parameter in wiringPi? I tried this:
    #include

    #include
    #include
    #include

    int main (void)
    {
    int pin ;
    int bitCount ;
    int bits;

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

    bitCount = 16 ;
    if (bitCount > 32) bitCount = 32;
    if (bitCount < 1) bitCount = 1;
    bits = 0;
    while (bitCount) {
    bits < 32) bitCount = 32;
    if (bitCount < 1) bitCount = 1;
    bits = 0;
    while (bitCount) {
    bits <<= 1;
    bits |= 1;
    bitCount–;
    }
    pwmWrite(1, 400);
    delay (1000);
    return 0 ;
    }

    but didn't work.

    Thank you.

    • If you want to control an RC type servo, then you’ll need to do more than that.

      Firstly, the SoC outputs a “balanced” form of PWM which isn’t suitable, so you need to put it in to traditional mark:space ration mode. Then there’s the working out of the clock frequency, the range and the values.

      It’s not something I’ve really looked into – I’d suggest you look at the “servoblaster” module – search the raspberry Pi forums for it – it will drive more than one servo too.

      -Gordon

        • If I get time in the next few days, I might have a go at servos myself. I have actually written a new module in wiringPi for servos, but I know it will suffer from the same jitter my softwarePWM does.

          WordPress mangles what you type – it doesn’t like < and > characters…

          -Gordon

  32. Hi Gordon,

    sorry for bugging you again…. I was using your library, works well… but as I worked on further with my code, the pwm for my lights flickered…. Any ideas why it flickers? Does that mean my code is too “heavy” on the library? 0__0

    Thanks for any kind opinions!!

    • It flickers because the Pi is doing other things while trying to maintain the accurate timing loop to keep the LEDs at a constant brightness. So even though it tries to make it run as a high-priority real-time thread, it can still be interrupted – things like network/usb and SD card accesses will be the worst culprits.

      The real solution is to do the PWM in the kernel where it can have more accurate control over the timings, or use a “proper” hardware PWM type chip, but for now that’s about the best we can do.

      I have had good results just with computationally heavy tasks – I think it’s accessing other hardware that can cause more flickering.

      -Gordon

  33. Hi Gordon,
    Im doing some development and have come as far as controlling some relays to move a motor adjusting the heating in my radiators in the house. I got a temperature probe to read the temp and adjust the heating accordingly. What I want to extend this project to is: My heating system is using pellets (small round wooden pieces), they are feeded to the burner with the help of an electrical motor. I have connected a relay to that motor to get a closed contact whenever it runs. I want to connect that relay to the GPIO as an input and count for how long its been running (it runs for x seconds whenever the burner needs pellets), print that runtime to a txtfile which I later pickup and enter into a mysql database.

    The problem I have is the part to count the time from rising edge to falling edge on the input and output that time (in ms) to a textfile.

    Could you or someone smart enough in the comments show me an example?

    • Shouldn’t be too hard – if (say) one second resolution is all you need. Pseudo code might look like:


      cycle
      wait for motor running
      start clock (note the return value of time (NULL); )
      wait for motor stopped
      stop clock
      subtract start time from stop time
      store in database
      repeat

      The actual wait can be a simple loop that polls the GPIO input pin (remember to use a pull-up or pull-down, depending on how you’ve wired it) and waits for it to change state. To conserve CPU time, it only needs to poll every few milliseconds – or even just once a second – assuming the motor will always run for longer than one second.

      If you really do need millisecond accuracy (and a relay probably takes a good few mS to move!) then it’s still do-able. You just need to use a higher resolution timer (gettimeofday()) to read the time and calculate the difference accordingly. In your poll loop, use delay (1) ; that’ll pause for one millisecond and free up the CPU – and have minimal impact overall.

      If you want “super accuracy” (whatever that is 😉 then you might need to re-code to use interrupts, but really, for mechanical motors and relays in this sort of application, I suspect anything in the range of a 10th to 1 second is more than accurate enough

      My woodburners are manually fed… 3 logs every hour…

      The Drogon Office Fire

      almost time to light it up too…

      -Gordon

      • Ok, I just need accuracy in seconds. So polling should be the best solution and not using interupts?

        Which would be like:
        int time = 0
        cycle start
        check if gpio pin is high
        if high time++
        check if gpio pin was high and now is low
        if so, write time var to textfile then set time to 0
        delay(1000)
        repeat cycle

        and make the program a deamon to run in background on pi?

        • It’s easier – which might turn out to be better as it’ll be faster to get going IMO…

          I’d not keep a counter though and would use the system time() call – see man 2 time for the details.

          C code fragment:

          for (;;)
          {
          while (digitalRead (boilerPin) == LOW)
          delay (100) ;
          start = time () ;
          while (digitalRead (boilerPin) == HIGH)
          delay (100) ;
          end = time () ;
          runTime = end - start ;
          printf ("We ran for %d seconds\n", runTime) ;
          //write to file
          }

          etc.

          -Gordon

  34. Have you tried working with the Clock generation feature on the chip? (pages 105-108 on the datasheet). It would be really awesome if your wiringPi has some easy functions to allow us to set the clock pins to generate certain frequencies (by selecting the right source and divider). I have been trying to generate 2.4Mhz clock from a C code but I failed to understand the datasheet or find other sources that are easy to work with.

  35. Dear Gordon

    Have any example of how to count and saving bit pulses
    incoming for a pin of the rasperry pi

    Thank lot

    • I’ve no examples, however it’s not going to be that straightforwards on the Pi – mostly due to timing issues – if you want to sample the pin at a fixed interval then there is a chance of missing a pulse. The hardware is capable of latching rising or falling edges, but that’s not implemented in wiringPi yet – it’s also capable of generating an interrupt – tricky, but that might help you, but the biggest issue really is accurate pule timing – so if you need that then I fear you’ve an uphill struggle…

      -Gordon

  36. Hi, i’ve noticed that wiringPi has UART functionality, at the moment i have my UART tx/rx looped. I have minicom open and in terminal i run “sudo echo – “testing testing 1 2 1 2″ > /dev/ttyAMA0” and can see the text testing testing 1 2 1 2 in minicom. My question is can i write a program using wiringPi that would give the same output? Like printf but for /dev/ttyAMA0?

    Thanks
    -Matt

    • If you have a look at the wiringSerial.c/h files, then you’ll find a serialPrintf () function – it works the same way a printf, but you give it a handle/file descriptor of the serial port you opened..

      So..

      if ((fd = serialOpen (“/dev/ttyAMA0”, 115200)) < 0) { fprintf (stderr, "Unable to open serial device: %s\n", strerror (errno)) ; return 1 ; } serialPrintf (fd, "Hello, world: %d\n", 6 * 7) ; will work for you. (check baud rate though!) -Gordon

  37. Hey Gordon, thanks for your help with everything! I have a question. I am trying to rig up my Pi so that it can flip a switch on a 9v relay. Do you have any suggestions on how I can accomplish this? I would really rather not use a chain of relays or a DC/DC converter, but that might be my only option. I was hoping there might be a way to wire 3 of the GPIO pins in series to achieve the 9v, but I don’t think this is possible.

    • Hi,

      Please don’t connect 3 GPIOs together – that really won’t work.

      You need a transistor to act as am amplifier and buffer for the relay. (and a diode to protect the transistor from back emf) If you were doing more than one, I’d suggest using an IC like the ULN2003, but for just one relay it’s a bit overkill (however it is easy to use!)

      You’ll need to know the current the relay takes to trigger and that will dictate the make of the transistor you use. A very quick google shows this:

      http://www.mouser.com/catalog/supplier/library/STSmallSignal.pdf

      and I’m sure you’ll find what you need.

      -Gordon

  38. Hi, thanks for all the work, I hope you have time to help me solve a problem.

    I’m using an up to date raspbian install, kernel info “3.2.27+ #250 PREEMPT Thu Oct 18 19:03:02” on a v1 (256Mb) board.

    I am trying to receive and decode the signals from a standard RC receiver. This is encoded as variable length pulses within a given time frame. I use edge detection the both directions and record the time differences to do the decode. There are 6 channels, so I use 6 pins to read with.

    With wiringPiSetupSys(), I can just about get stable readings from all 6 channels. Sadly if I then try to do anything like play audio in response to an input, then the accuracy drops for my channels to the point where it is not usable.

    I need less overhead and jitter, but when I swap to wiringPiSetupGpio() or wiringPiSetup() I don’t seem to be getting any interrupts at all ?

    (Have tried both “native” and wiringpi pin numbers.)

    Any thoughts ?

    • Hi,

      Are you using interrupts? ie. code based on the ‘wfi.c’ example program?

      If so, then there is an upper limit to the number you can handle/second. (and its about 20,000 in total)

      (and I am familiar with Radio Control stuff! I could rant on for hours about how dated and prehistoric I think it is, however it still seems to be going strong, why? I don’t know!)

      So you need to detect a pulse width of between 1 and 2 mS, and 6 of them by the sounds of things.

      You should probably be running 6 concurrent threads, each at the same priority (but higher than the main program) – so then, they ought to not be interrupted by any user-land code – sadly, the kernel will interrupt them to do things like service audio, etc.

      Alternatives might be to use something like xrf/urf, xbee, etc. for the comms – then you can send high-level messages over the air and not RC’s PPM/PWM, however if you are stuck with it, then you can front it with an Arduino, etc. where there is plenty of existing code doing this very task – e.g. Ardu Pilot, etc.

      -Gordon

      • Thanks Gordon,
        I am helping out on a project with a non existent budget that is pushing my boundaries.

        The RC rx/tx combo is existing kit as are the expensive Roboteq boards that drive the main motors.

        The *main* requirement is to be able to trigger audio output by toggling one or more channels on the rc tx, this I could do by only monitoring the channel(s) used for the audio this would reduce the load to the point that I can make it work.

        I know however that autonomous action will be a future requested feature, requiring that I be able to intercept all 6 channels.

        My problem is with the accuracy of the timings when going though all the layers that Sys() has to go through. It’s not that much better than the pure python code I started with. Latency *after* the decode is not yet a concern.

        I have a small c program that hooks into wiring pi and looks after one channel. Around that I have a multi threaded python program that launches 6 instances of my c code.

        I know it’s a mess, two weeks ago I had never worked in c or python.

        I’m hopeful that if I can figure out why I cannot use Gpio() that the performance may be there without having to go bare metal.

        • Interrupts need to go throught the Sys() mechanism. So if you’re using interrupts, then you need to initialise with wiringPiSetupSys() – afer using the gpio command to do the neccessary level export settings.

          If you’re not using interrupts and purely polling the pins, then you can use native, or Gpio() setups methods.

          However, if polling, then I’d use one loop and poll each of the 6 pins one after the other, rather than 6 threads.

          If your python program is lauching 6 instances of a C program, then it’s using Linues fork() mechanism and creates 6 new processes which is fine, but it’s a bit resource wasteful.

          email me your C code if you like.

          -Gordon

  39. This code does NOT work. If I call wiringPiSetupSys() it does.

    #include
    #include
    #include
    #include
    #include
    #include

    int main (int argc, char* argv[])
    {
    if (argc != 2)
    {
    printf (“1 argument – gpio pin number”) ;
    }
    else
    {
    struct timeval one_time, two_time;
    double one_pulse, two_pulse, combo_pulse;

    int ires , pin , skipcheck , status , checkstatus , checkstatus2;

    int dataPtr ;
    int l, s, d ;

    pin = atoi(argv[1]);

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

    pinMode (pin, INPUT) ;

    one_pulse = 0;
    two_pulse = 1;
    skipcheck = 1;
    gettimeofday(&one_time, NULL);
    status = 0;
    checkstatus = 0;
    checkstatus2 = 0;

    while (1)
    {
    ires = waitForInterrupt (pin, 60000);
    gettimeofday(&two_time, NULL);
    two_pulse = (double)(two_time.tv_usec – one_time.tv_usec)/1000000;
    if (ires == 1)
    {
    if (skipcheck == 0)
    {
    combo_pulse = one_pulse + two_pulse;
    // printf (“%f\n”,two_pulse) ;
    if (combo_pulse > .0195)
    {
    if (combo_pulse < .0205)
    {
    if (two_pulse < .003)
    {
    if (two_pulse .00095)
    {
    skipcheck = 1;
    checkstatus2 = 1;
    // fwd
    }
    }
    if (two_pulse > .00147)
    {
    if (two_pulse .00185)
    {
    if (two_pulse < .002)
    {
    skipcheck = 1;
    checkstatus2 = 3;
    // bkwd
    }
    }
    }
    }
    }
    }
    else
    {
    skipcheck = 0;
    }
    }
    else
    {
    }
    one_time = two_time;
    one_pulse = two_pulse;
    if (checkstatus – checkstatus2 == 0)
    {
    if (status != checkstatus2)
    {
    // previousstatus = status;
    status = checkstatus2;
    if (status == 1)
    {
    // printf ("1\r\n") ;
    std::cout << "1" << std::endl;
    }
    if (status == 2)
    {
    // printf ("2\r\n") ;
    std::cout << "2" << std::endl;
    }
    if (status == 3)
    {
    // printf ("3\r\n") ;
    std::cout << "3" << std::endl;
    }
    }
    }
    checkstatus = checkstatus2;
    }
    }
    return 0 ;
    }

  40. I understand now. Gpio() == no interrupt support.

    Okidoki, looks like I’m left with two choices, neither I like the looks of.

    1) Bare metal.

    2) Since there is direct access to physical memory though /dev/mem there *should* be a way to intercept the system irq vector and deal with the interrupts directly.

    Thanks for the help anyway.

    • There is a way to mix native/gpio mode with Sys() mode, however in this instance you won’t gain anything. Most of the time taken is going to be Linux processing the interrupt, then re-schedulling your program (that’s program, not process – this is heavyweight schedulling here).

      It could be a lot more efficient if you have just one C program to monitor all the inputs, but then, it looks like you’re using stdout to communicate back to your (Python?) program – and that’s another area of slowness. You’re making Linux schedule & re-schedule many different programs for your task.

      Why not do it all in C?

      You can not simply poke /dev/mem to change interrupt vectors into your own code. Linux doesn’t like that. If you want better interrupt handling then you need to write a kernel module – in C.

      -Gordon

  41. Was *just* thinking that there might be a third option of writing a driver as a kernel module.

    Though for me that’s as big a leap as going to bare metal, as you can tell from my convoluted setup.

    I think I might have my new years resolution.

    If I can do this, then I feel usb host support for the pi coming from a port of http://www.obdev.at/products/vusb/index.html

    • I can think of easier ways to talk to an ATmega type chip from the Pi’s point of view…

      I also think your program could beenfit from a better or fully C solution. 2 (or more) processes communicating via stdout/stdin is not very efficient and neither is forking off 6 programs from a Python program. You could handle the decoding of the 6 inputs in a C program, then write the values to shared memory for example (but I don’t know if Python supports shared memory – I’m not a Python programmer)

      -Gordon

  42. I agree a full C solution is in order. I am currently looking into what it takes to compile said code.

    The point of the USB code is NOT to run it on an ATmega. As the bulk is C code, compile and run it on the pi to get a usb HOST interface on the pi.

    If a 6mips microcontroler can do 1.5Mb as a usb host and have some processor time left over, then surely the pi can as well.

    • I wonder if we’re at cross purposes here.. The Pi already has a USB host interface… That’s the 2 rectangular sockets on the side next to the Ethernet socket…

      The big issue with the Pi isn’t mips, or clock speed, it’s latency and jitter – things you find hard to control with a multi-user, pre-emptively multi-tasking operating system like Linux. Even “bare metal” you have the dram refresh and video ram memory refresh to contend with too – unlike on a microcontroller with static RAM and precise timings.

      -Gordon

      • 12MHz ?

        Low speed is 1.5 MHz no ?

        If a microcontroler clocked at 24Mhz with 4 cycles per instruction can do it ?

        • I don’t think you’re quite comprehending what I posted earlier….

          You may get close in a “bare metal” type scenario, but it’ll never fly under Linux.

          -Gordon

  43. Great job Gordon, “wiringpi” is a great brilliance peace of software!
    Big Thank You and Well Done!

    Ivan

  44. Great job!
    I have checked RPi.GPIO which is written only based on python.
    And I get a result that the best way to control things on Rspi is the WiringPi python wrapper!
    Fast and functional.

    Thank you, Gordon!

  45. Gordon.. Firstly.. great job..

    I have installed wiringpi on my raspberrypi and am using a sample from http://www.raspberrypi.org/phpBB3/viewtopic.php?t=16118&p=191051 to control 4 motors that I have linked to using http://shieldlist.org/adafruit/motor.

    I have hooked up all the pins and seem to have everything ready but when I run the code executable even though it says its applying pwm absolutely nothing happens!

    Is there anything else I need to install to be able to use the Arduino motor shield or is wiringpi enough?

    • OK… First things first…

      Use the gpio command to manually set the right pins to output, then to set them on/off to test the motor functionality. It might be worthwhile using an LED & resistor just to make sure you have the right pin numbers too.

      The code there looks OK – just remember that to control the motor, you need 3 pins – 2 are the direction control and one is PWM – you can set the PWM high, then play with the 2 direction controls – usually they are both low to let the motor freewheel, both high to ‘brake’ the motor (ie. short the coils) and one high, one low to make it run one way, and vice versa for the other way. (I may have the signals the wrong way round though, do check the docs!)

      Also make sure the power supply is OK – are you using a separate PSU for the board?

      Other than that, do double-check the wiring.

      -Gordon

  46. Hi Gordon,

    In you title pic there appears to be an old stone arch. Looks like a good place for a metal detector.

    • Not much metal on old stone though.. It’s actually a folly called Mow Cop Castle, and not a place of any special significance.

      More details here: http://en.wikipedia.org/wiki/Mow_Cop_Castle

      I was sitting in the round window to the right in the bottom photo and the photo was taken from the other side (it’s just a wall!)

      -Gordon

  47. Hi Gordon,

    I’d be interested if anyone knows how to build the latest version of wiringPi (circa. 15 Jan 2013) on Arch Linux. I have a version of i2c-dev.h installed from package linux-api-headers but it doesn’t define the required functions. Therefore make fails with “warning: implicit declaration of function ‘i2c_smbus_read_byte’” etc. I’ve tried installing lm_sensors, which contains some additional related headers, but still no luck. There doesn’t seem to be a libi2c-dev package for Arch.

    Would appreciate it if anyone can help.

    Thanks

    Dave

    • Delete the reference to wiringPiI2C.c in the Makefile in wiringPi and re-build.

      Not a perfect solution but it’ll give you everything else.

      Did the ./build script stop? It should have detected that the standard version if i2c-dev.h was installed and not the development one that wiringPi needs…

      -Gordon

      • Gordon – yes, your ./build script detected the std i2c-dev.h and stopped, so I’m trying to build with just make/make install in the appropriate directory. The above work-around (del ref to wiringPiI2C.c in Makefile) appears to give a good build (make runs successfully) but the installed wiringPi libraries don’t work for me (i.e. my LCD driver no longer runs).

        For now, I’ve discovered that returning to an earlier version of wiringPi (6 Dec 2012) is best for now. n.b. this can be done with:

        cd wiringPi
        git log
        git checkout 25e4ec57

        This version builds cleanly and my LCD runs OK.

        Thanks for the help so far.

        Dave

        • You’re using Arch then? Looks like I’ll need to work out how to install the i2c-dev libraries & headers in Arch…

          Not sure why it’s broken though – my suspicion is timing in the LCD driver, but I thought I fixed that a while back.

          -Gordon

          • Gordon,

            Yes, I’m running an up-to-date Arch system. Kernel 3.6.11-3-ARCH+.

            Appreciate any help.

            Thanks – Dave

  48. Hi Gordon,

    i have problems during the make of gpio. I’m running raspbian and libi2c-dev is installed in the newest version.

    The make of wiringPi finished without any errors.

    The error message is:

    ——————————————————————-
    [Compile] gpio.c
    [Link]
    /usr/lib/gcc/arm-linux-gnueabihf/4.6/../../../libwiringPi.so: undefined reference to `i2c_smbus_write_byte’
    /usr/lib/gcc/arm-linux-gnueabihf/4.6/../../../libwiringPi.so: undefined reference to `i2c_smbus_read_byte’
    /usr/lib/gcc/arm-linux-gnueabihf/4.6/../../../libwiringPi.so: undefined reference to `i2c_smbus_write_byte_data’
    /usr/lib/gcc/arm-linux-gnueabihf/4.6/../../../libwiringPi.so: undefined reference to `i2c_smbus_write_word_data’
    /usr/lib/gcc/arm-linux-gnueabihf/4.6/../../../libwiringPi.so: undefined reference to `i2c_smbus_read_word_data’
    /usr/lib/gcc/arm-linux-gnueabihf/4.6/../../../libwiringPi.so: undefined reference to `i2c_smbus_read_byte_data’
    collect2: ld returned 1 exit status
    make: *** [gpio] Fehler 1
    ——————————————————————-

    DO you have any ideas?

    Thanks in advance.

    Best Regards,
    Stefan

    • I can’t see why it wouldn’t work if you have libi2c-dev installed )-:

      Best thing to do is

      ./build clean
      ./build uninstall

      then edit wiringPi/Makefile

      and remove wiringPiI2C.c from it, then

      ./build

      again.

      I’ve tried to do blind/fresh installs on Pi’s with and without i2c-dev to make sure it finds the right thing, but obviously on your Pi there is something that either you don’t have that I do, or vice versa, so I’m going to have to emove the (experimental) I2C stuff I’ve put in so-far.

      Sorry.

      -Gordon

      • Thanks for the fast reply! 😀 You’re great. It’s working now.

        Just if you are interested in… I’m running a Raspberry Pi V2 with a mininal Raspbian (Raspbian Installer). I’ve applied all available updates with apt-get -u dist-upgrade) and rpiupdate.

        Stefan

  49. Hi,

    I came across this tonight and was having issues. With some of the return codes, and yet the strerrors were all trues… The errors I was getting looked like so:

    root@raspbmc:/etc/wiringPi# WIRINGPI_DEBUG=1 gpio mode 0 out
    gpio: wiringPi debug mode enabled
    wiringPi: Debug mode enabled
    wiringPi: wiringPiSetup called
    piboardRev: Revision string: Revision : 000f
    piboardRev: lastChar is: ‘f’ (102, 0x66)
    piBoardRev: Returning revision: 2
    wiringPiSetup: mmap failed (timer): Success
    gpio: Unable to initialise wiringPi mode

    Anyway, I made some *very* minor changes and gpio is now working perfectly. Here’s my patch in case it can help anyone else:

    diff –git a/wiringPi/wiringPi.c b/wiringPi/wiringPi.c
    index 36c49f5..ef68e38 100644
    — a/wiringPi/wiringPi.c
    +++ b/wiringPi/wiringPi.c
    @@ -1214,7 +1214,7 @@ int wiringPiSetup (void)
    if ((int32_t)gpio == -1)
    {
    if (wiringPiDebug)
    – fprintf (stderr, “wiringPiSetup: mmap failed: %s\n”, strerror (errno)) ;
    + fprintf (stderr, “wiringPiSetup: mmap failed: %s — %d\n”, strerror (errno), errno) ;
    return -1 ;
    }

    @@ -1231,22 +1231,25 @@ int wiringPiSetup (void)
    // Clock control (needed for PWM)

    clk = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, CLOCK_BASE) ;
    – if ((int32_t)clk < 0)
    + if ( ((int32_t)clk < 0) && (errno != 0) )
    {
    if (wiringPiDebug)
    + fprintf (stderr, "The error code is %d\n", errno);
    fprintf (stderr, "wiringPiSetup: mmap failed (clk): %s\n", strerror (errno)) ;
    return -1 ;
    }

    // The drive pads

    +/*
    pads = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, GPIO_PADS) ;
    – if ((int32_t)pads < 0)
    + if ( ((int32_t)pads < 0) && (errno != 0) )
    {
    if (wiringPiDebug)
    fprintf (stderr, "wiringPiSetup: mmap failed (pads): %s\n", strerror (errno)) ;
    return -1 ;
    }
    +*/

    #ifdef DEBUG_PADS
    printf ("Checking pads @ 0x%08X\n", (unsigned int)pads) ;
    @@ -1256,7 +1259,7 @@ int wiringPiSetup (void)
    // The system timer

    timer = (uint32_t *)mmap(0, BLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, GPIO_TIMER) ;
    – if ((int32_t)timer < 0)
    + if ( ((int32_t)timer < 0) && (errno != 0) )
    {
    if (wiringPiDebug)
    fprintf (stderr, "wiringPiSetup: mmap failed (timer): %s\n", strerror (errno)) ;

    • Hi,

      Thanks for that – it’s highlighted a few other issues too, so I’ve made some changes based on your patches, and pushed a new version out. If you want to pull it and see if it’s working better for you.

      -Gordon

  50. Hi. I am unable to get wiringPi working on my rev2 board in turbo mode, I get: gpio: Unable to initialise wiringPi mode. I am using raspbian with latest updates (and rpi-update). With WIRINGPI_DEBUG I get this:

    # gpio readall
    gpio: wiringPi debug mode enabled
    wiringPi: Debug mode enabled
    wiringPi: wiringPiSetup called
    piboardRev: Revision string: Revision : 000f
    piboardRev: lastChar is: ‘f’ (102, 0x66)
    piBoardRev: Returning revision: 2
    wiringPiSetup: mmap failed (pads): Success
    gpio: Unable to initialise wiringPi mode

    Any ideas?

    • The above is after I commented-out the clk mmap code in wiringPi.c as it is actually the clk mmap that fails first:

      wiringPiSetup: mmap failed (clk): Success

      Phil

      • Try a

        git pull origin
        ./build

        in the wiringPi directory and see if that helps. I’ve noticed a few issues with some new code I’ve included.

        -Gordon

  51. I’m trying to bit-bang a serial tx signal through a GPIO pin at 4200 baud using delayMicroseconds(417); and digitalWrite(); but it seems to suffer from a lot of lost/corrupt data. I added piHiPri(90) at the start which helped a lot but didn’t sort it all together.

    Is the RaspPi under Linux not that reliable as accurately timed bit-bashing or is it likely I’ve got a dodgy wire? (I’ll try using UART/I2C/SPI whih I presume has hardware support.

    MrW
    (PS: Thanks for the library)

    • You’re right at the limits of what’s achievable I’m afraid.

      So when running it at high priority what you have done is to efectively stop all other user-land processes running, however, the delayMicroseconds() call will deschedule your program and then allow them to run again – until your program is ready to run… However Linux doesn’t guarantee that delay – it’s a minimum of that delay and may be more….

      Also, there are things going on in the background – such as the USB & Ethernet processing (something on your LAN sends an ARP request that the kernel needs to reply to for example), or an internal timer fires on the Pi and the kernel needs to update it’s time-of-day clock, and so on.

      And even if you turn all that off, there is the GPU which handles the memory refresh cycles and updating the video memory and you can’t turn that off at all…

      So you can get close, but not be perfect – things that are close enough are the softwarePWM library I wrote and the softTone library (but using that, you can hear the occasionaly glitch!)

      So really the way is to use a peripheral device – there is the on-board UART (but I’m assuming you were already using that hence the need to bit-bang) but if you needed a 2nd, I’d probably look at a USB device myself…

      (If you’re not using the on-board one, but want to, then look at the wiringSerial code for a simple way to get going with it)

      -Gordon

      • (Oh quick response! Thanks)

        Yeh, as I expected. I’ve avoiding the UART as I need an “IDLE on low” serial connection and inverting the logic didn’t seem to work. I might revisit that solution. The bit-banging approach works on the Arduino so I thought I’d port it to the Pi using your fabby library. (All this to avoid buying the PICAXE proprietary serial cable – £15!!)

        All jolly good stuff.

        • Arduino doesn’t have a full-blown multi-tasking operating system running on it…

          Or you could dump all that PIC stuff and stick to ATmega 😉

          However a simple transistor & a couple of resistors ought to be enough to invert the signal. Guess you might need to to correct the signal back into the Pi, so 2 of them – might also provide votage buffering if the PIC system is at 5v too…

          -Gordon

          • Yeh tried all that (reassuring to have my opinion confirmed). No joy though. I suspect there is some annoying difference between what I think a UART signal/protocol looks like and what it actually is. Up until now I have been thinking I need a digital storage oscilloscope – until my mate VERY kindly dropped one round at my house today. WHAT A GENT!
            So I’ll do some debugging and get it working and write it up on-line. THEN I’ll get on and look at ATmega perhaps.

  52. Hey, this is exactly what I need. I’m running a Pi as a headless music player, and would like some GPIO pins to go high or low soon after the Pi boots. I placed the requisite commands inside a script file, made the script executable, and used update-rc.d to make it (hopefully?) launch at boot.

    But, (you guessed it), nothing happens. I can launch the script manually via ssh and it works. Is there something special I should be doing to make a pin stay low or high at boot?

    • If using the gpio command, make sure you specify the full path, so /usr/local/bin/gpio, or set the $PATH variable in the script to include /usr/local/bin.

      -Gordon

      • Success! Adding PATH=/usr/local/bin:$PATH before the gpio calls fixed the problem. Thanks a bunch!

  53. hello,
    i try to test wiringpii2c but fail on i2c_smbus_read_byte etc. i’ve the i2c-dev.h file but cannot find any i2c_smbus_read_byte_data etc. i’m using archlinux 3.6.11-4-ARCH+. Any help is appreciated.

    • My suggestion is to move from Arch to Raspbian. It all works there just fine. Alternatively, get in-touch with the Arch maintainers and persuade them to create an i2c-dev package the same as the Debian one.

      Or, you can download the debian i2c-dev.h file from http://unicorn.drogon.net/i2c-dev.h and put that in-place of the one in /usr/include/linux/i2c-dev.h and see if that helps you…

      -Gordon

  54. Is there a way to escape a null character with SerialPutS or do I have to use SerialPutChar ?

    Thanks for this wonderful utility!

    • No, you need to use serialPutchar – nul is 0 and that’s what terminates strings in C.

      However, you can use write() – the file descriptor returned by serialOpen is a standard Linux file descriptor, so if you have a buffer of arbitary binary data, then:

      write (fd, buffer, length) ;

      is what you need. But you need to know the length of-course! Have a look in the source code and you’ll see that that’s exactly what serialPuts() is doing itself.

      -Gordon

  55. Hello Gordon,
    I have your ladder-game pcb, which operates fine! And I am learning Bash!
    I want to operate a 28byj-48 5v stepper motor using wiringPi. The motors are inexpensive and come with a Darlington driver board for £2.90 + PP. Do you have (or can point me to) any wiringPi examples of Stepper programs?
    Thanks.

    • Wish I could help, but I’ve never used QTCreator…

      However a quick google…

      Firstly get and install the wiringPi/I2C stuff as per normal:

      cd
      sudo apt-get install libi2c-dev
      git clone git://git.drogon.net/wiringPi
      cd wiringPi
      ./build
      gpio -v # Just to check

      Then you need to add in an external library – google is showing me stuff to do with the Windoes version, but I imagine it’s the same or simlar for the Linux version – add in wiringPi as an external dynamic library located in /usr/local/lib with the header files in /usr/local/include. I think that should be fairly straighforwards, but without actually trying it myself I can’t be sure.

      -Gordon

  56. Hi Gordon, I’m starting with Pi and curious thing happens, I can’t handle some pins (GPIO 2, SDA0, SCL0, GPIO 8, GPIO 9, GPIO 10and GPIO 11) with WiringPi numbers, when I use GPIO or a C programm, using GPIO with BCM GPIO numbers is OK.
    Can you help me? Can I use BCM GPIO numbers in C programms? How?

    Thanks

    Valdir

    • It sounds like you’re mostly sorted from reading the next post – but wiringPiSetup() gives you wiringPi pin numbers, and wiringPiSetupGpio() gives you BCM_GPIO pin numbers. Be aware that on a Rev 2 Pi, BCM_GPIO pins 0, 1 and 21 have moved to 2,3 and 27. If you stick to wiringPi numbers then they don’t move between board revisions.

      Also make sure that you don’t have the I2C and SPI modules loaded too – they may interfere with your ability to use the pins you mention here.

      -Gordon

  57. Hello!

    Your library worked great for me, untill I have installed the EW-7811Un WiFi adapter. Suddenly, gpio readall says that outputs are high, but I cannot light a single led.
    I hope it is not a hardware damage, but I would love to hear your opinion (if it’s possible that I could somehow damage software).

    Worried Paul

    • Struggling to think why plugging in a Wi-Fi adapter would upset the GPIO. The obvious check would be to remove the Wi-Fi adater and try without if you can.

      The adapter ought to be just another USB peripheral and I’ve had a few different USB devices plugged into my Pi’s without any issues (never Wi-Fi though – not something I need myself)

      But other than checking with it removed, I’m at a bit of a loss here…

      -Gordon

  58. Hello!

    Thank you for the reply. I just wanted to make sure – I mean I wouldn’t connect anything wrong, so I have no clue why would gpio broke. The only possibility is transportation, but if so, then rpi is very fragile.

    I did test it without wifi adapter, no changes at all.

    Worst thing is it isn’t my rpi, and now I don’t even know how to explain this situation.

    Anyway, the libraries are great, I love C based stuff. Thanks for the reply.

  59. i get this error and cant understand

    im using WP version 1.12

    pi@raspberrypi ~/projects/MagPi $ sudo python magpi.py
    Traceback (most recent call last):
    File “magpi.py”, line 5, in
    import nokiaSPI
    File “/home/pi/projects/MagPi/nokiaSPI.py”, line 14, in
    import wiringpi
    ImportError: No module named wiringpi

    • Wish I could help, but I didn’t write the Python wrappers for wiringPi, just the underlying C library calls. It sounds like you may not have wiringPi installed though, but I’ve really no idea how it interacts with the Python wrappers (I don’t program in Python myself)

      -Gordon

      • its odd as i tried a C version code and that works just fine

        i only get errors on the python code

        i personally am more a C person but have beed looking into Unix and Python

  60. Greetings to you all, spring is on the way!
    I REALLY agree with the huzzahs for the wiringPi libs! I am connecting my own small board for standard Hitachi-type displays to be able to use I2C instead of parallel connection. The small board is well tested connected to my ARM equipped CPU boards. The small board uses a ATtiny461 for control of the display. I do not succeed using the RPi thou… Now my question: When using RPi and looking on the output, the SDA and SCL it looks OK BUT for the clock period for the ACK bit. The clock high time for the data bits are 5 us or longer, the ACK bit is approx 2 us (I use 1MHz clocking in the logic analyzer) after the first byte sent. My ATtiny461 do not accept the short clock pulse, it seems. Are the clock pulses software generated, is it possible to lengthen all of them to 5 us high time? (I can send a .png image as illustration!)
    Otherwise everything all right here in Sweden… Nils in Uppsala

    • I’m just providing wrappers round the standard kernel drivers – and there are some issues there that I’m aware of – the Pi doesn’t like clock stretching, so if the device is doing that operation to dealy the ack back to the Pi, then it will probably fail.

      You can lower the I2C data rate – if you use the gpio command to load the I2C module, then

      gpio load i2c 50

      shoudl set the baud rate to 50,000 bps.

      That might help? (or might not!)

      -Gordon

      • Hello, thanks for the answer. I have reprogrammed my ATtiny461 to accept short clock now… Are there, or will it be an API function to send strings via I2C in your I2C-lib?
        Nils

        • If you want to send strings, you can simply write() the data to the file desriptor – as long as the I2C device can accept arbitary binary data sent to it.. e.g. write (fd, bufer, size) ;

          -Gordon

          • You was right, again: “…as long as the device can accept…” The USI hardware in ATtiny461 cannot handle continuous data… So one char at a time must do… (But sending from a AT91SAM7S256 stringwise is alright. They do a proper repeated START condition.)

      • Hello, thanks for the answer. I have reprogrammed my ATtiny461 to accept short clock now…
        I have recorded a sequence where the 8th clock was too short (approx 2 us) but the ACK clock was OK. Something to look into?

        Are there, or will it be an API function to send strings via I2C in your I2C-lib? Sending the char’s one by one does function, though…
        Nils

  61. Thanks! Will try!
    Did try. Now the last (8th) bitclock pulse AND the ACKclock pulse are 2 us.

    To more important things:
    Your Drug Baron is beautiful, I love redheads! The other ladies are very good looking too, tell them that!
    73’s
    Nils

  62. Hi Gordon,

    I’m using your WiringPi utility, which is really great, so thank you for your effort. However, I have a relatively simple question. What are the states when RPi is booting? Is IO by default in output or input mode and if output mode, is output HIGH or LOW? I don’t have the necessary tools right now to test it out. Thank you.

    • Until recently all the GPIO pins were set to input by default at boot time. However with the release of the 3.6.11+ kernel it appears that 2 pins (BCM_GPIO 0 and 1) are now set to outputs with their output held low. These are the I2C pins on a Rev 1 board – on a Rev 2 board they’re still I2C, but are now internal to the Pi.

      Because they’ve now changed and becuse the foundation have changed pin function between the Rev 1 and Rev 2 boards, I would not rely on the state of any GPIO pin at boot time. Most of them will be inputs, but as I found out just yesterday, 2 are now outputs.

      -Gordon

    • It’s ok Gordon,

      gpio readall says all 🙂
      When RPi boots, all GPIO’s default state is INPUT mode and all values are LOW.

      • Try that on a Rev 1 Pi and you’ll see something different.

        +----------+-Rev1-+------+--------+------+-------+
        | wiringPi | GPIO | Phys | Name | Mode | Value |
        +----------+------+------+--------+------+-------+
        | 0 | 17 | 11 | GPIO 0 | IN | Low |
        | 1 | 18 | 12 | GPIO 1 | IN | Low |
        | 2 | 21 | 13 | GPIO 2 | IN | Low |
        | 3 | 22 | 15 | GPIO 3 | IN | Low |
        | 4 | 23 | 16 | GPIO 4 | IN | Low |
        | 5 | 24 | 18 | GPIO 5 | IN | Low |
        | 6 | 25 | 22 | GPIO 6 | IN | Low |
        | 7 | 4 | 7 | GPIO 7 | IN | Low |
        | 8 | 0 | 3 | SDA | OUT | Low |
        | 9 | 1 | 5 | SCL | OUT | Low |
        | 10 | 8 | 24 | CE0 | IN | High |
        | 11 | 7 | 26 | CE1 | IN | High |
        | 12 | 10 | 19 | MOSI | IN | Low |
        | 13 | 9 | 21 | MISO | IN | Low |
        | 14 | 11 | 23 | SCLK | IN | Low |
        | 15 | 14 | 8 | TxD | ALT0 | High |
        | 16 | 15 | 10 | RxD | ALT0 | High |
        +----------+------+------+--------+------+-------+

        Also note that the I2C pins will not read low on a Rev 2! You must have something connected to them – they will read HIGH by default due to the on-board pull-up resistors.

        Rev 1:

        +----------+-Rev2-+------+--------+------+-------+
        | wiringPi | GPIO | Phys | Name | Mode | Value |
        +----------+------+------+--------+------+-------+
        | 0 | 17 | 11 | GPIO 0 | IN | Low |
        | 1 | 18 | 12 | GPIO 1 | IN | Low |
        | 2 | 27 | 13 | GPIO 2 | IN | Low |
        | 3 | 22 | 15 | GPIO 3 | IN | Low |
        | 4 | 23 | 16 | GPIO 4 | IN | Low |
        | 5 | 24 | 18 | GPIO 5 | IN | Low |
        | 6 | 25 | 22 | GPIO 6 | IN | Low |
        | 7 | 4 | 7 | GPIO 7 | IN | Low |
        | 8 | 2 | 3 | SDA | IN | High |
        | 9 | 3 | 5 | SCL | IN | High |
        | 10 | 8 | 24 | CE0 | IN | Low |
        | 11 | 7 | 26 | CE1 | IN | Low |
        | 12 | 10 | 19 | MOSI | IN | Low |
        | 13 | 9 | 21 | MISO | IN | Low |
        | 14 | 11 | 23 | SCLK | IN | Low |
        | 15 | 14 | 8 | TxD | ALT0 | High |
        | 16 | 15 | 10 | RxD | ALT0 | High |
        | 17 | 28 | 3 | GPIO 8 | IN | Low |
        | 18 | 29 | 4 | GPIO 9 | IN | Low |
        | 19 | 30 | 5 | GPIO10 | IN | Low |
        | 20 | 31 | 6 | GPIO11 | IN | Low |
        +----------+------+------+--------+------+-------+

        -Gordon

      • This isn’t really a forum as such – more really intended for comments & feedback for my wiringPi project… However I’m working on a new site with forums and so on, so that may be a better place, but it’s at least a week away yet.

        Really not sure what you’re after here either though – it’s a clock that runs on a PIC – it’s not really designed to be interfaced to anything.

        -Gordon

  63. import wiringpi
    wiringpi.wiringPiSetu
    serial = wiringpi.serialOpen(‘/dev/ttyAMA0’,9600) // Requires device/baud and returns an ID
    wiringpi.serialPuts(serial,”hello”)
    wiringpi.serialClose(serial) // Pass in ID

    Am a noob with serial and just trying to get some action on my Tx pin. It seemed to be working when I ran this code. But no when I run it I get nothing on the O-Scope and instead just get a constant 3V3. No clue why :'(. Any advice, people? Thanks, I appreciate it

    • I’ve no idea what language that is, but it’s not C – which is what I support for wiringPi. I’m guessing you’re using something else which has a wiringPi wrapper?

      However, first thing I’d check is that you have the right pin. I’d also use minicom to check it initially before moving on to programs.

      -Gordon

      • Sorry I should have been more clear. I’m utilizing a raspberry pi and the wiringpi-python from github. I need to find a way to check if /dev/ttyAMA0 is correct, but cannot find how at the moment.

          • Gordon, thanks for the speedy reply. For some reason it seems like my TXD and RXD are default outputting a constant 3V3. I’ve looked over the RPi GPIO manual and cannot figure out if this is normal, while I believe this could be a reason or symptom of what is wrong with my Pi. Sorry if I’m bothering you with simple questions.

            Thanks.

          • Double-check that you’re using the right pins.

            Use the gpio command with a multimeter or LED to check –

            gpio -g mode 14 out ; gpio -g write 14 0
            gpio -g mode 15 out ; gpio -g write 15 0

            that would put them both to 0v. You’ll need to reboot the Pi to get them back into serial mode.

            Use the pins page: http://wiringpi.com/pins/ to make sure you’re using the right pins.

            -Gordon

  64. Thanks for the suggestion. This worked when issuing in command line, both pins set to 0V. Rebooted and both pins defaulted to 3V3.

    What is weird is that I had this working for a short time. By working, I mean I could run the above python script and see a response on the oscilliscope. Then, had to run to class, come back, and of course I’m getting no response.

    I’ve read above that you want this section to be questions and comments on your wiringpi library and not a forum, so let me know if I should post elsewhere, or what other troubleshooting steps I may be able to take.

    • It’ going to be a few days before I get my forums ready (sorry).

      quite confused why you can see the lines wiggling with the gpio command but not when sending serial data though. I don’t have an answer for that though!

      -gordon

  65. Inside ~/wiringPi/examples $: gcc pwm.c -o Tpwm
    get:
    * /tmp/ccYLGr7I.o: in function ‘main’:
    * pwm.c:(.text+0xc): undefined reference to ‘WiringPiSetup’
    * plus 7 more similar errors plus
    * collect2: ld returned 1 exit status
    also
    /usr/local/lib/ contains files: libwiringPi.so.1 and libwiringPi.so.1.0
    and
    /etc/ld.so.conf contains text: include /etc/ld.so.conf.d/*.conf
    and
    /etc/ld.so.conf.d/ contains files: 00-vmcs.conf, arm-linux-gnueabihf.conf and libc.conf
    libc.conf contains text: /usr/local/lib/ per your notes.
    uname -a gives Linux raspberrypi 3.6.11+ #371 PREEMPT Thu Feb 7 16:31:35 GMT 2013 armv6l GNU/Linux
    any guidance welcome
    Aim is to run HO train with PWM on 18 + sound + direction controls and a few lamps/switches.

    • You haven’t linked in wiringPi! Please read all the documentation, Makefiles, etc. and add -lwiringPi to the compile line.

      -Gordon

  66. Thanks for the suggestion of a boot script to resolve the issue of needing to be root in order to export the pins. It works well, but is probably not as clean as a good script writer could produce.
    #!/bin/bash
    # Setup script for pin functions using gpio
    # This script should go in /etc/init.d/
    # Make the script executable: sudo chmod 755 /etc/init.d/exportPiPins.sh
    # After testing (sudo /etc/init.d/exportPiPins.sh), register the script
    # to run at boot time: sudo update-rc.d exportPiPins.sh defaults
    # You should modify the script to export the pins you need so they will
    # be available to user programs. The pin numbers are BCM-GPIO pins.
    # See web or documentation for mapping to physical pins.

    ### BEGIN INIT INFO
    # Provides: gpio17
    # Required-Start: $network $syslog
    # Default-Start: 2 3 4 5
    # Required-Stop: $network
    # Default-Stop: 0 1 6
    # Short Description: Export Pins
    # Description: Export Pins at boot and unexport pins at shutdown
    ### END INIT INFO

    # Author: Mike Beaver
    # Thanks to Gordon@Drogon.net for pointing out that a boot script would resolve
    # the problem with needing root privileges to do anything with the gpio pins.
    # Once the pins are exported, his WiringPi utilities and library work just fine
    # for a normal non-root user. Just the thing for a headless web server to run your
    # sprinklers, heating system, or ……

    case “$1” in
    start)
    echo 0 > /sys/class/gpio/export
    echo 1 > /sys/class/gpio/export
    echo 4 > /sys/class/gpio/export
    echo 9 > /sys/class/gpio/export
    echo 10 > /sys/class/gpio/export
    echo 11 > /sys/class/gpio/export
    echo 17 > /sys/class/gpio/export
    echo 18 > /sys/class/gpio/export
    echo 22 > /sys/class/gpio/export
    echo 23 > /sys/class/gpio/export
    echo 24 > /sys/class/gpio/export
    ;;
    stop)
    echo 0 > /sys/class/gpio/unexport
    echo 1 > /sys/class/gpio/unexport
    echo 4 > /sys/class/gpio/unexport
    echo 9 > /sys/class/gpio/unexport
    echo 10 > /sys/class/gpio/unexport
    echo 11 > /sys/class/gpio/unexport
    echo 17 > /sys/class/gpio/unexport
    echo 18 > /sys/class/gpio/unexport
    echo 22 > /sys/class/gpio/unexport
    echo 23 > /sys/class/gpio/unexport
    echo 24 > /sys/class/gpio/unexport
    ;;
    esac
    :

    • If it works, it works!

      Pesonally,I’d do something like:

      for i in 0 1 4 9 10 11 17 18 22 23 24; do /usr/local/bin/gpio export $i; done

      -Gordon

  67. Hi Gordon,

    Been research and learning with RPi and Gpio..
    I am deaf person, I been setup a door bell notification to pushingbox then to my mobile phone so it vibrate let me know when someone is at the door…

    Everything is work fine and boot up self, but few thing need to be clean up..
    – CPU 100% usage all time,
    – doorbell press it notification me twice.

    the script of doorbell.py is

    #!/usr/bin/env python
    import RPi.GPIO as gpio
    import urllib, urllib2
    gpio.setmode(gpio.BCM)
    gpio.setup(11, gpio.IN)
    key = “XXXXXXXXXXXXX”
    class pushingbox():
    “””
    Sends the notification to pushingbox
    “””
    def __init__(self, key):
    url = “http://api.pushingbox.com/pushingbox”
    values = {‘devid’: key}
    try:
    data = urllib.urlencode(values)
    req = urllib2.Request(url, data)
    SendRequest = urllib2.urlopen(req)
    except Exception, detail:
    print “Error”, detail

    while True:
    input_value = gpio.input(11)

    if input_value == True:
    print(‘The button has been pressed ……. :)’)
    # When the button is pressed, trigger the pushing box scenario
    pushingbox(key)
    while input_value == True:
    input_value = gpio.input(11)

    im worry abt the 100% cpu may heat up the cpu?

    thanks
    Ant

    • RPi.GPIO is not wiringPi – it’s a Python GPIO library – I’m really not familiar with it (nor Python). You’d be best off posting on the forums rahter than the comments here for wiringPi.

      -Gordon

  68. Hi Gordon

    Thanks for the gertboard code in wiring Pi. I had to adapt it a bit for the ADC and DAC I bought. I thought you may wish to see my changes:

    The DAC is RS Stock No. 681-1092 Brand Microchip Mfr Part No. MCP4822-E/P.

    For which I had to change gertboardAnalogWrite to:

    int gertboardAnalogWrite (int chan, int value)
    {
    uint8_t spiData [2] ;
    uint8_t chanBits, dataBits ;
    int iret;
    if (chan == 0)
    chanBits = 0x30 ; // gain x1 , active, channel A
    else
    chanBits = 0xB0 ; // gain x1 , active, channel B

    chanBits |= ((value >> 8) & 0x0F) ;
    dataBits = (value & 0xFf) ;

    And the ADC is MCP3002 2.7V Dual Channel 10-Bit A/D Converter

    For which I had to change gertboardAnalogRead:

    int gertboardAnalogRead (int chan)
    {
    uint8_t spiData [3] ;

    int iret;

    if (chan == 0)
    spiData [0] = 0b01100 ; // single ended channel 0
    else
    spiData [0] = 0b01110 ; //single ended channel 1

    spiData [1] = 0 ;
    spiData [2] = 0 ;

    if( (iret = wiringPiSPIDataRW (SPI_A2D, spiData, 3))<0){
    printf("Error returned by wiringPiSPIDataRW %d",iret);
    }
    return (spiData[1] <> 5 );
    }

  69. buenas noches gordon e empesado a trabajar en raspberry pi y vi tu pagina en la cual das un software o librerías en lenguaje c++ tengo un simple duda yo ya instale las librerías ta cual como usted recomienda como empresaria a trabajar en lenguaje c++ que plataforma genera la instalación de wiringpi al iniciar la raspberry no encuentro una plataforma en a cual se puede programar y ejecutar el código le agradezco si me saca de esta duda soy de colombina y pues estamos tratando de difundir el software libre en la ciudad para usos de eletronica de potencia gracias

    • Using Google translate – I /think/ you want example programs? Look in the examples directory in the wiringPi download. There are some written in C there.

      -Gordon

  70. Gordon,

    I previously posted on an issue I was having, but I wanted to check….What should be the default voltage on the TXD pin?

  71. Dear Gordon,
    I’am working for the first time with Makefiles. In simple programs (they contain only one source file) I’am using your Makefile to build my Projects. But when it comes to more source files, which should be build to a single program, I don’t know what to add to the Makefile…
    Could you create an example for a Makefile with at least two C-files and one header?
    Thanks a lot!

    • IF you fetch the Halloween Pi code:

      cd ; git clone git://git.drogon.net/halloweenPi

      and look at its Makefile. That is one program that is comprised of 3 files and a header file!

      The stuff at the bottom – underneath the # DO NOT DELETE line is re-constructed with the

      make depend

      command. It searches the source files and constructs the dependancy list – so make then knows what files to re compile if you change any other file.

      -Gordon

  72. HO TRAIN INTERFACE – READ THE SMALL PRINT – I just read your entertaining note on PWM output being one of the audio channels! After reloading ALSA I’m back to testing sound and my ‘logic’ now has the interesting feature of playing ‘sound’ on the HO track voltage. I should have sent you a schematic, you’d have seen the ‘crash’ coming a mile away. So hopefully I can find someway of limiting the sound to one channel and getting back control of PWM on wPi-1. It’s like a Rubik’s cube; wondering if you can get there from here!

  73. Bonjour,

    Grand merci pour l’aide en ligne !
    je viens de faire mon entrée dans le monde de GPIO de RaspBerry PI
    A bientôt

  74. I am working on Raspberry Pi Model B.

    I am trying to interface the accelerometer (https://www.sparkfun.com/products/10955) device over the I2C Bus on the Rpi.

    My hardware Connections are:-

    RPi Accelerometer

    Vcc P1_1 ——————Vcc

    Gnd P1_9 ——————Gnd

    SDA P1_3 ——————SDA

    SCL P1_5 ——————SCL

    I am using the wiring Pi Library.

    I compile the code by the command pi@raspberrypi ~/acc $gcc main.c acc.c -lwiringPi

    and run it with the command

    pi@raspberrypi ~/acc $ sudo ./a.out

    I do the following before executing my code

    pi@raspberrypi ~/acc $ gpio load i2c

    pi@raspberrypi ~/acc $ i2cdetect -y 1

    0 1 2 3 4 5 6 7 8 9 a b c d e f
    00: — — — — — — — — — — — — —

    10: — — — — — — — — — — — — — 1d — —

    20: — — — — — — — — — — — — — — — —

    30: — — — — — — — — — — — — — — — —

    40: — — — — — — — — — — — — — — — —

    50: — — — — — — — — — — — — — — — —

    60: — — — — — — — — — — — — — — — —

    70: — — — — — — — —

    Here I am getting the correct slave address, but when I try to read anything from the device I always a 00 from the device.

    My code is at https://github.com/khandharjay/Rpi-I2C

    Anything that I am missing out.

    I would appreciate the help

    • Your code looks OK, but if you read 0 from register 0x0D then something somewhere might not be right.

      Tracking it down might be tricky though.

      Have you tried: i2cget -y 0 0x1d 0x0d

      That might at least confirm the device is working properly, then we can look elsewhere…

      -Gordon

      • I tried doing i2cget -y 1 0x1D 0x0D. This is a WHO_AM_I register in the device and its value is 0x2A.

        But I get 0x00.

        Note–I did i2cget -y 1 0x1D 0x0D, because the command i2cdetect -y 1
        shows me the slave address of my device (0x1D).

        • ok – bus 1 – Rev 1 Pi.

          So if the generic register read command isn’t working, then I wonder if there is some other communication issue – however i2cdetect finds it OK. It does seem a bit odd and I’m slightly confused myself here…

          -Gordon

          • I have tried hooking up a logic analyser on the SDA and SCL pins. What I found was that the raspberry Pi was putting correct logic levels on the bus, but when the slave had to put something on the bus ( like in a read operation), the SDA line would always stay low.

  75. I got the Accelerometer working. It needs a repeated start signal. I used the hipi library, which internally uses the wiring Pi I guess.

  76. Gordon,
    A huge thank you for putting this together! I just finished a group semester project and this library was a huge help. We put together the old Simon game using a Raspberry Pi. I threw it up on youtube if you’re interested in checking it out. http://www.youtube.com/watch?v=GmE3ANOYYOY

      • Yeah we used softTone for the speaker that coordinates with the LEDs. Another huge thanks for that part because we never would have figured out how to get different notes out of that speaker

  77. Using WiringPi with Lazarus/FreePascal, and it works great. Thank you for making it available. I learned a lot by studying your source code.

    Thanks again for your work.

    Curt Carpenter

  78. Hi Gordon I tried to contact you via email but to no avail. I’ve created a C# wrapper class for your WiringPi libraries which include I2C and SPI, the reason being that although there’s already a RaspberryPi.Net solution it uses bit banged SPI which I think is rather poor and inefficient.

    I just wanted to let you know in case you want to place a link on your site to the wrapper. It can be found on github: https://github.com/danriches/WiringPi.Net
    Other information pertaining to using it is located on my blog, yes it’s sparse as I’ve only just started:
    http://danriches.blogspot.co.uk/

    Hope this is helpful to anyone out there BUT please be aware that this is only in development stage and SPI is the only thing I’ve tested out so far…

    Have Fun and thanks for the great library, you’re a star!!

    Dan

  79. Hi Gordon,
    Great work.

    What I’m trying to do is have some switches connected as inputs that would allow me to control different parameters of raspistill without having it connected to anything (running headless outside). All this in a C-program.

    For example,
    A switch (BUTTON_PREVIEW) would control preview (-p) parameter of the raspistill. ON = preview, OFF = no preview.

    This way I can ran the pi + the camera headless outdoors and use various switches to control things like (resolution, iso, time, etc) without modifying the code. My program would call raspistill in a loop and check the state of the switch before executing.
    Something along these lines:

    [code]
    for ( c=1; c<=3000; c++ )

    // BUTTON_PREVIEW would be connected to an input pin
    if (digitalRead(BUTTON_PREVIEW) == HIGH)
    PREVIEW = "-p 0,0,400,400";
    else
    PREVIEW = "-n";

    raspistill -t 100 -w 1920 -h 1080 -q 90 PREVIEW -o /home/pi/%04d.jpg;
    delay(1000);
    [/code]

    Is something like this possible?

    Thanks,
    Tom

    • You can do it in BASH easilly. Have a look at the tuxx.sh program in the ladder board section of my GIT repository:

      git clone git://git.drogon.net/ladder

      -Gordon

  80. Hai,

    Anyone played with the BH1750FVI and Raspi V2 ?
    Would like to get it running but not finding any good src.. all is for the arduino and not sure if this is a good Wire.h replacement…

    Maybe someone can help me out here ?

    Chrs Paul.

  81. Hi!

    WiringPi’s functions doesn’t work when I compile it with OpenCV…

    I wrote a program that is using WiringPi to get information from an accelerometer. This program is working just fine, but when I use some OpenCV instructions to do some video treatment, the WiringPi’s functions doesn’t work any more. This happen when I add OpenCV’s libraries to the compilation.

    Does somebody know how to fix this?

      • Absolutely no errors at the compilation…
        But at the execution wiringPiI2CSetup returns 7 so I used perror to have more details and I got : “No such file or directory”. But with the same program when I do no use OpenCV wiringPiI2CSetup returns 3 and perror returns “Success”.

  82. Hi
    WiringPi setup is works correctly and fine i am really thankfull to @Gordon. but there is a problem regarding wiringPiSetup its showing me error when i am running my executable in an infinite loop
    its working fine for 5-10 minutes after this an
    Error is always occured :

    wiringPiSetup: Unable to open /dev/mem: Too many open files

    please show me some footmarks of yours on this problem

  83. Hi,
    thank you for your really nice work.
    I’m programming with Lazarus/Freepascal on my Pi and using Rpi_hal to read/write the GPIO of a PiFace …
    Now i need more GPIO then 8/8;E/A … i’ve read about PiRack to connect up to 4 PiFaces to one PI … my problem is, how can i read to a PiFace with an other ID (JP1/2; default ID0, for example to ID1) …
    do you have any idea?

    Thanks a lot
    – Tom

    • The piface library was really only designed to drive one PiFace.

      However using the mcp23s17 library, you can drive lots of them… Although it wouldn’t be too much work to add in a change to the PiFace library to support more…

      I’ll have a look.

      -Gordon

      • Hi Gordon, that would be very nice additinal function for the future by using the pi for a complex construction 🙂

        Thanks a lot
        – Tom

  84. Hi Gordon. First of all thanks for y help. I am using wiringPiISR for interrupts, but this function run the callback in other thread.
    I want to stop my main progam, run the interrupt and then return to the main program is that possible?.

  85. hey gordon i have a starting trouble with my Rpi..can you tell me how to configure the pins in Rpi..being a beginner i dont know how and where to start.

  86. Hi, Gordon, I need your help. Sorry for my bad English, I’m Cuban. I’m great fan of your library.
    I need to make a periodic task in the rpi.
    I need a frequency of at least 20 Hz and no more than 1 KHz.
    I have achieved this by using gettimeofday or clock_gettime in a loop, waiting to get to the right moment. My results are very close to my needs, but i really want to do this in a more efficient way, because i will do other task in the pi (example: image processing).
    Is there a way I can use the kernel, a timer, a scheduler, or anything else, to do this?
    Is there any other library I could use?
    Thanks in advice.

      • I was specting to get something more elegant, perhaps an interrupt handler, like the one you have implemented in your library for the rising and falling edge in GPIO.

        • Well… You can trivially implement this yourself – no need for wiringPi for it. You create a thread, have that thread wait, then have that thread call a function at the appropriate time. The thread runs concurrently with your main program. Welcome to the world of threaded programming… See/Search for pthreads.

          -Gordon

      • I was expecting to get something more elegant, perhaps an interrupt handler, like the one you have implemented in your library for the rising and falling edge in GPIO.

        • I have already used the threads, and i think this is very powerful tool.
          Sorry if I bother you with my questions. But it’s very important to me to solve this problem and I know that you have the knowledge to show me the way to go.
          But the fact is i know that people use handlers for interrupts in gpio pins. I want to use interrupts for the 1 MHz timer running in pi, for example.
          Is that possible?
          How the kernel deal with the interrupts in gpio pins?

          • OK. Didn’t realise you were tied to a GPIO pin. Looks like you’ve had a reply on the forums, but simply put, you’ll not get 1MHz interrupts to a user program on the Pi. Best I got was 66KHz. See my writeups and examples. (Looks for isr-osc.c)

            -Gordon

  87. Thanks for that great library.

    I have a question related to the “interrupts” with the RPI;
    Weirdly, if you put a printf in a call back function, triggered by a physical “pull-up” circuit, the interrupt function ‘wiringPiISR’ calls the callback function multiple times (arround 5-6).

    In the other hand, if you put some delay in the callback function, lets say 2000ms, its seems to be called only once…

    I guess the RPI is confused with the input state for few milliseconds and therefore triggers the callback function multiple times. What do you think ?

    • I think you’re seeing switch bounce.

      Simulate the interrupt with the pull up/down resistors like it suggests in the example files with no hardware connected and see what happens…

      -Gordon

      • Arg, you were right, its not good for me though!
        I guess I ll have to do a de-bouncing circuit with a capacitor… May be i could handle it programmatically by editing your ‘wiringPiISR” function?
        Is there some push-buttons more suitable than other to avoid bouncing?

        Thank you,

        Martin

        • Do it in software. Take the first interrupt, then set a flag/store the current time (use gettimeofday()) then on the next interrupt, if it’s less than about 20mS since the first, then ignore it (and re-set the 20mS timout)

          That’s a fairly typical way to handle debouncing.

          -Gordon

  88. after running the program serialTest.c in my pi it is showing error as
    undefined reference to ‘serialopen’
    undefined reference to ‘millis’
    undefined reference to ‘wiringPiSetup’
    undefined reference to ‘serialGetchar’
    undefined reference to ‘delay’
    undefined reference to ‘serialdataAvail’.
    Can you help me solve this problem please….