Skip to content

Tutorial: How to use your Raspberry Pi like an Arduino

2012 June 15
by Tedb0t

Finally got to experiment with the Raspberry Pi’s GPIO (General Purpose Input/Output) pins.  I tried three methods: Python, Bash and C, and will describe each.  But first, here’s some setup information.

  • Connecting to the RPi’s GPIO header: I used an old floppy disk drive IDE ribbon cable.  It has 34 pins, but the RPi’s header is only 26 pins, so part of the connector is unused. I soldered some breadboard-friendly header pins onto the other end, which is working pretty well so far. Bear in mind that some IDE cables may be more complicated than they look. Before powering anything up, make sure you check that each conductor is indeed separate and you’re not accidentally grounding or shorting anything. You can always make your own by getting some 26-conductor IDC connectors and using a vice to crimp it onto a piece of ribbon cable.
  • Pin Connections: …are confusing! There’s a master table here, and a diagram here.  Looking at the diagram, my breakout header starts with 3.3V and moves left to right, top to bottom.  Here are the pin connections from my header as pictured:
    • Pin 2: 5V
    • Pin 3: “GPIO0″. Connected to one end of the switch (the other end is connected to ground, since this GPIO pin has an internal pull-up resistor.  This means that when the switch is not closed, the pin reads as “High,” and when closed, “Low.”
    • Pin 6: GND (note that it’s jumpered to my ground rail on my breakout board)
    • Pin 7: “GPIO4″. The anode of the LED through a 220-ohm resistor.
  • I’ll use this breakout board setup for all the following examples.  Different libraries/tools use different pin numbers, adding to the confusion, so I’ll try to clear it up.  Also note that I’m doing this through an SSH session, so there’s no monitor attached to the RPi. See my beginning instructions here if you don’t already have an SSH connection to your Pi.
  • Important Note: The RPi Wiki takes pains to remind you that these GPIO pins are unbuffered and unprotected, so if you short something out, you could fry your whole Pi, so be careful!  There are a number of other breakout boards being developed that should make this safer.
  • Important Note: Any program that accesses the GPIO pins must be run as root, so if you get an error, remember to “sudo” your command.
  • Python: One of my preferred languages, so I figured I’d try it out. First, install pip (Python package installer):
    • sudo curl | python
    • Next, install the RPi.GPIO Python module:
    • sudo pip install rpi.gpio
    • Now, you can enter the python interpreter (sudo python) and do stuff like:
    • import RPi.GPIO as GPIO
      GPIO.setup(7, GPIO.OUT)
      GPIO.output(7, True)
  • Bash: Something I’ve always loved about Unix is the idea that everything is a file.  On the Raspberry Pi, the GPIO pins are files too! With the pictured breadboard setup, we can do the following to turn the LED on and off (note that this uses the “BCM” pin numbering but the breadboard stays the same!):
    • (You can’t just put sudo before each command because the second command that the output is directed to would not be run as root. So, for simplicity, we drop into root first.)
      sudo su -
      echo "4" > /sys/class/gpio/export
      echo "4" > /sys/class/gpio/export
      echo "out" > /sys/class/gpio/gpio4/direction
      echo "1" > /sys/class/gpio/gpio4/value
      echo "0" > /sys/class/gpio/gpio4/value
    • To read from an input, ‘cat’ it like any other file!
      echo "0" > /sys/class/gpio/export
      echo "in" > /sys/class/gpio/gpio0/direction
      cat /sys/class/gpio/gpio0/value
  • C: Good old C.  The native example for C is really hairy, but luckily a plucky fellow named Gordon wrote an Arduino-like library just for the Raspberry Pi!  Here’s what you need to do:
    • Download and install the library:
      cd /tmp
      tar xfz wiringPi.tgz
      cd wiringPi/wiringPi
      sudo make install
      cd ../gpio
      sudo make install
    • Your Pi’s system now has the wiringPi library installed, so we can write a little program that uses it.
      cd ~
      nano blink.c
    • Type or paste in this program:
    • And compile it:
      cc -o blink blink.c -L/usr/local/lib -lwiringPi
    • And run it:
      sudo ./blink
    • You should have a happily blinking LED. Yay! Now for something more interesting:
  • Where’s my analogRead?  Sadly, unlike an Arduino, the RPi doesn’t have an onboard ADC (Analog to Digital Converter). However, some of the breakout boards being designed will include an external ADC, such as the Gertboard.  You can add your own external ADC, such as this one, by using the SPI bus on the RPi (the MOSI, MISO and SCK pins).
  • That’s all for now! Hope this helps, and as always, let me know if it works or you run into any problems.

Related Posts:

  • bnewbold

    I believe the reason that sudo doesn’t work for the “echo” commands is that you are sudo-ing the echo command but not the bash pipe redirect:

    $ sudo echo “hello world” > ~root/thing bash: /root/thing: Permission denied

    One way to get around this is with the ‘tee’ command:

    $ echo “hello world” | sudo tee ~root/thing

    I’m curious if there is a more idiomatic method.

    • T3db0t

      Ah, that makes sense. Thanks!

    • rhqq

      or even better sudo sh -c “echo asdadasd > /some/where”

  • Pingback: MAKE | How-To: GPIO on Raspberry Pi

  • Pingback: How-To: GPIO on Raspberry Pi | Indoor Digital Billboards

  • Chris

    I run into the same sudo issue when I try to drop the extra memory buffers in Linux. Everything up to the re-direction is run as root, but the pipe or the chevron breaks it into a new command, run my myself instead of root. tee is the way to go, as bnewbold stated.

  • Pingback: Using the GPIO pins on a Raspberry Pi - Hack a Day

  • Joonas Pihlajamaa

    Nice post! Have you yet found out the performance specs of the RaspPi GPIO – i.e. what kind of frequencies and bandwith can be achieved for example when compared to 8-bit microcontrollers which often lack the clock cycles for anything above 1-2 MHz?

    By the way, I’ve recently done a level shifting article that may be useful to those wanting to protect their 3.3V RaspPis:

    • RayZ

      they have them on youtube at 100 mhz playing fm radio.

  • Wouter

    Is it possible to communicate with a webserver?

  • Jean-Damien POGOLOTTI

    You’re missing to include stdlib.h in the C example code. Compiling will fail on the exit() statement. (using the std debian image)

    • T3db0t


  • Jeremy

    Can the GPIO pins generate a PWM signal for controlling things like hobby/rc servos?

  • minimdr

    Could this code be used with my Raspberry PI? It is running on an Arduino board to control leds on a reef tank.

    byte MoonPhase()


    int m,d,y;

    int yy,mm;

    long K1,K2,K3,J,V;

    byte PWMvalue;

    m = month();

    d = day();

    y = year();

    yy = y-((12-m)/10);

    mm = m+9;

    if (mm>=12) mm -= 12;

    K1 = 365.25*(yy+4712);

    K2 = 30.6*mm+.5;

    K3 = int(int((yy/100)+49)*.75)-38;

    J = K1+K2+d+59-K3;

    V = (J-2451550.1)/0.29530588853;

    V -= int(V/100)*100;

    V = abs(V-50);

    PWMvalue = 4*abs(50-V); // 5.12=100% 4=~80%


    return (PWMvalue*100)/255;


    returns 0-100.

    can comment the kast line and return PWMvalue for 0-255.

  • Gordon


    Good article and thanks for the link to wiringPi!

    But can I make a suggestion or 2 :)

    wiringPi is currently under constant development and the one you’ve linked to is a bit old now (well, old as in a few weeks, but things change quickly here!)

    So – the instructions really ought to be:

    cd /tmp

    tar xfz wiringPi.tgz
    cd wiringPi/wiringPi
    sudo make install
    cd ../gpio
    sudo make install

    If you stick to just using the wiringPi.tgz filename, it will always pull the latest version down.

    And there’s also a separate GPIO program – the GPIO program allows you to do GPIO operations from the command-line without needing to be root!


    gpio -g mode 18 pwm
    gpio -g pwm 18 750

    (range is 0-1023)

    Additionally, I recently added features into it to allow the export/unexport from the command-line
    too (again without the need to be root), so it’s worthwhile checking for updates.



    • Ted Hayes

      Thanks! I updated the instructions. Any chance you might host the code on github? :)

  • flo35


    In my case, i connect a button on 26 pin.

    The state of button isn’t always good (True / false)
    I have connect a pull-up resistor beetween 3,3V pin and 26 pin.
    I resolve my problem :)

    am i alone with this bug ? i have a raspberry pi model B
    my debian distribution ?

    • flo35

      For information : It’s OK Now, commit/update
      RPi.GPIO 0.2.0 -> RPi.GPIO 0.3.1a :) with pull-up internal

      • Ted Hayes

        WIthout the pull-up (or pull-down) resistor, the pin is said to be “floating.” It will have spurious voltages due to surrounding electromagnetic fields, which is why you get an unreliable reading.

  • Pingback: IO Pin Control « Raspberry Pi Projects

  • evollidaw

    Great tutorial, thanks!

  • Michael

    I have some old I/O cards laying around, and the parallel port ribbon cable is a perfect fit for the GPIO headers. This also gives a nice option of putting the Pi in a case and having the DB-25 female connector on the other end to give easy access to GPIOs (and put those old printer cables to some use).

  • Eugene Plaksienko

    I have problem, I have no pip command, but python is there, any ideas? Thanks

  • Eugene Plaksienko


    I get error message

    building ‘RPi.GPIO’ extension
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.7 -c source/py_gpio.c -o build/temp.linux-armv6l-2.7/source/py_gpio.o
    source/py_gpio.c:23:20: fatal error: Python.h: No such file or directory
    compilation terminated.
    error: command ‘gcc’ failed with exit status 1

    on sudo pip install rpi.gpio

    Any ideas? Thanks

    • Eugene Plaksienko

      Disregard guys, I found the answer

      • Qaz

        Well, what is the answer then? I’m having the exact same problem.

        • random.random()

          sudo apt-get install python-dev

  • Victor

    thanks for your post. Its being helpful for my work. I’m having some problems.

    Everything it’s running ok until I try to compile it, then I receive lots of errors.

    blink.c: 33.1: error: stray ’302′ in program
    blink.c: 33.1: error: stray ’240′ in program
    blink.c: 33.1: error: stray ’302′ in program

    and so on.

    Some one can help me?


    • Jason Hoffman

      I had the same error. What’s happening is that when you cut and paste the code into the nano editor it’s reading odd carriage returns from the web browser into nano. Just load the blink.c program into nano again and delete the carriage return from before each line then hit return and it should insert a correct return. Do this with every line and those should go away when you compile.

      • Victor

        thanks, i have wrote it from the beginning and the problem has gone. It was what you have said.


  • Pingback: My experience with the Raspberry Pi |

  • dchurch

    It might be worth mentioning that the default Wheezy image doesn’t include setuptools.
    Resolve this by doing:

    sudo apt-get install python-setuptools

    before the ‘curl’ command.

    • Vernon Breet

      Thanks for this.

  • floid

    I just received my new 512 Pi. I’m able to compile the code with no errors, but my LED doesn’t work. I can make it go on and off using the bash commands, so I know the wiring is correct. I even added an extra printf within the loop and the loop is working. I just can’t get the LED to do anything with the C examples. Please help…


  • Ignacio

    Hi, I’m thinking to buy an arduino leonardo, but recently I have discoverd raspberry pi. Can I do the same with an arduino than a Raspberry pi?, obiously raspberry pi is a computer and I supose that the probabilities are more biggest. Thanks.

  • rubiconcowboy


  • Pingback: Raspberry Pi, como comecei (conversa de café) – blog (arquivo) do nsa

  • Pingback: How to use your Raspberry Pi like an Arduino

  • Pingback: How to use your Raspberry Pi like an Arduino — Arduino Passion

  • Pingback: Anonymous

  • dougm

    Another quick note, I deduced from bnewbold’s post below that everything after a pipe wasn’t run with root permissions. The problem I was having was that python wasn’t able to create directories. So I switched from this:

    sudo curl | python

    to this

    sudo curl | sudo python

    and it worked better.


  • michel

    i hope you can help me with this issue.
    I’m using the Python example and it all works great.
    Now i’m also trying to run the python script from PHP, but then the import statement can not be resolved. Is that something you have seen before?

  • beginner

    /usr/lib/gcc/arm-linux-gnueabi/4.6/../../../ reference to `i2c_smbus_write_byte’
    /usr/lib/gcc/arm-linux-gnueabi/4.6/../../../ reference to `i2c_smbus_read_byte’
    /usr/lib/gcc/arm-linux-gnueabi/4.6/../../../ reference to `i2c_smbus_write_byte_data’
    /usr/lib/gcc/arm-linux-gnueabi/4.6/../../../ reference to `i2c_smbus_write_word_data’
    /usr/lib/gcc/arm-linux-gnueabi/4.6/../../../ reference to `i2c_smbus_read_word_data’
    /usr/lib/gcc/arm-linux-gnueabi/4.6/../../../ reference to `i2c_smbus_read_byte_data’
    collect2: ld returned 1 exit status
    make: *** [gpio] Error 1
    Do you know what this error means? I get it when i run “make” in /tmp/wiringPi/gpio folder.

    • Andrew Hazlett

      Has anyone figured out what is going on when this error happens?

      • OldMercenary

        Same, getting this error too.

        • David Blackburn

          It seems to have gone wrong in the make for wiringPi where ther are warnings of “implicit declaration of function” for all the items for which there are undefined references. Maybe a source file or include has gone missing?

          • Haolde

            There seems to be a minor error in the makefile (or build script), thus a warning about the missing libi2c-dev may not always be issued. Go ahead and read the file “build”, follow the instructions to apt-get install the lib and do not forget to make clean. After that, a fresh build will recompile the wiringPi files with libi2c-support, and subsequently gpio will link alright.
            Hope you will get along, I went thru this the hard way too ;-)

    • lol

      the seg faults when u try to run it by itself

  • Senthir

    Check out how to orderly shut down your Raspberry Pi using the GPIO and a hard drive jumper:

  • Scott

    Just wanted to thank you for doing this. I was able to get the LED blinking and wanted to show my appreciation that you took the time to explain what you did. Thank you.

  • Ian

    Looking at the other comments, this probably sounds stupid, but where’s the tutorial? My computer is just showing the name of the article, the author, and the comment section, etc.

  • sim

    I can’t find the tutorial too… help please